美文网首页程序员
在UIView上添加触摸事件

在UIView上添加触摸事件

作者: 每日总结 | 来源:发表于2016-03-17 21:27 被阅读522次

    方法1.协议和代理
    在UIView中设置协议和代理属性

    #import <UIKit/UIKit.h>
    @protocol RootViewDelegate<NSObject>
    - (void)changeColor:(UIView *)view;
    @end
    @interface RootView : UIView
    @property (nonatomic, assign) id<RootViewDelegate> delegate;
    @end
    

    让UIViewController遵守协议并实现协议中的中的方法

    #import "RootViewController.h"
    #import "RootView.h"
    @interface RootViewController ()<RootViewDelegate>
    @end
    @implementation RootViewController
    - (void)changeColor:(UIView *)view{
        view.backgroundColor = [UIColor redColor];
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
        RootView *rootView = [[RootView alloc] initWithFrame:CGRectMake(100,100,100,100)];
        rootView.background = [UIColor whiteColor];
        rootView.delegate = self;
        [self.view addSubview:rootView];
        [rootView release];
    @end
    

    在UIView中调用协议方法

    @implementation RootView
    - (void)touchesBegin:(NSSet <NSTouch *> *)touches withEvent:(UIEvent *)event{
        if ([self.delegate respondsToSelector:@selector(changeColor)]) {
            [self.delegate changeColor:self];
        }
    }
    @end
    

    方法2.模拟UIControl的addTarget方法
    在UIView的.h文件中设置声明addTarget方法,并在.m中实现和调用方法

    @interface RootView : NSObject
    {
        id _target;
        SEL _action;
    }
    - (void)addTarget:(id)target action:(SEL)action;
    @end
    
    
    @implementation RootView
    - (void)addTarget:(id)target action:(SEL)action{
        _target = target;
        _action = action;
    }
    - (void)touchesBegin:(NSSet <NSTouch *> *)touches withEvent:(UIEvent *)event{
        [_target performSelector:_action withObject:self];
    }
    @end
    

    在UIViewController中调用addTarget方法

    #import "RootView.h"
    @implementation RootViewController
    - (void)viewDidLoad{
        [super viewDidLoad];
        RootView *rootVC = [[RootView alloc] initWithFrame:CGRectMake(100,200,300,400)];
        [rootVC addTarget:self action:@selector(rootVCAction:)];
        [self.view addSubview:rootVC];
        [rootVC release];
    }
    - (void)rootVCAction:(UIView *)view{
        view.backgroundColor = [UIColor redColor];
    }
    @end
    

    相关文章

      网友评论

        本文标题:在UIView上添加触摸事件

        本文链接:https://www.haomeiwen.com/subject/uxjtlttx.html