码迷,mamicode.com
首页 > 其他好文 > 详细

UIButton set touch handler in code

时间:2015-03-09 12:23:06      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

One option is to set the button up using

[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside];

but this is a bit dangerous because target is not retained so you could send the message to a deallocated object.

You could instead set up a protocol

MyController.h
@protocol MyControllerDelegate
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button;
@end

@interface MyController : UIViewController

@property (nonatomic, assign) id <MyControllerDelegate> delegate;

- (IBAction)buttonTapped:(UIButton *)button;

@end

Then in your implementation

MyController.m
- (IBAction)buttonTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
      [self.delegate myController:self buttonTapped:button];
    }
}

As the method defined in the protocol was not optional I could have instead done a check for (self.delegate) to make sure it is set instead of respondsToSelector.

UIButton set touch handler in code

标签:

原文地址:http://www.cnblogs.com/welhzh/p/4323057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!