And*_*Hin 17 cocoa-touch objective-c uibutton ios
我试图将UIButton子类化以创建一个"更智能"的按钮,其中包含用于处理click事件的逻辑.
实现这一目标的最佳方法是什么?我只需要覆盖onClick方法吗?或者我是否需要注册事件处理程序(如果是这样,应该在哪里查看,因为有很多方法可以初始化UIButton?)
kub*_*ubi 33
我认为这个问题比你提出的问题有更好的解决方案,但是直接回答你的问题:UIButton的子类以与其他人观察触摸事件相同的方式观察触摸事件.
// In your UIButton subclass
- (instancetype)initWithFrame:(CGRect)frame {
self = [super buttonWithType:UIButtonTypeCustom];
if (self) {
[self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)didTouchButton {
// do whatever you need to do here
}
Run Code Online (Sandbox Code Playgroud)
重要提示:您不能[UIButton buttonWithType:]
用来创建按钮,您必须使用init
或initWithFrame:
.即使UIButton具有便捷初始化程序,initWithFrame:
仍然是指定的初始化程序.