我的iOS学习历程 - TargetAction

什么是TargetAction?比如button继承于view,button可以通过添加点击事件来做出反应,但是view却不行,怎么让view也可以和button一样呢,这就是TargetAction的作用了:

首先我们自定义一个buttonView:
buttonView最重要的是需要两个属性:
1.action:需要实现的方法
2.target:谁来响应这个方法
所以我们需要重写初始化方法,把这两个属性添加进去(我们默认是关闭ARC以便于熟悉内存管理)

- (instancetype)initWithFrame:(CGRect)frame
                       target:(id)target
                       action:(SEL)action
{
    self = [super initWithFrame:frame];
    if (self) {
        //  初始化时 对属性 进行赋值
        self.action = action;
        self.target = target;

    }return self;   
}

接下来就是写方法,要在点击结束是执行命令的话:(四个方法尽量写全)
重点:让某个对象调用某个方法用哪个参数用 performSelector这个方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    //  使用self.target对象调用action方法
    //  让一个对象去调用这个对象类里面的方法
    //  Object 可携带的参数

    [self.target performSelector:self.action withObject:self];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

}

这样我们一个具备button点击功能的view就好了,让我们来试试让这个view在点击后改变颜色:
1.先创建一个buttonView:
target填self就是自己来响应后面填的buttonViewClick这个方法

ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 100, 100) target:self action:@selector(buttonViewClick:)];

2.接下来写改变颜色的方法:

- (void)buttonViewClick:(ButtonView *)buttonView{
    buttonView.backgroundColor = [UIColor colorWithRed:arc4random()%256 / 255.0 green:arc4random()%256 / 255.0 blue:arc4random()%256 / 255.0 alpha:1];
}

是不是很简单?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值