我正在尝试对UIButton进行子类化,以创建一个"更智能"的按钮,该按钮包含处理点击事件的逻辑。
实现这一目标的最佳方式是什么?我只需要重写onClick方法吗?或者我需要注册一个事件处理程序吗?(如果需要,有很多方法可以初始化UIButton,应该在哪里完成?)
我认为这个问题有比你提出的更好的解决方案,但要直接回答你的问题: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
}
重要提示:不能使用[UIButton buttonWithType:]
创建按钮,必须使用init
或initWithFrame:
。即使UIButton有便利初始化器,initWithFrame:
仍然是指定的初始化器。