Ios 子类UIButton并检测UIControlEventTouchUpInside
我尝试检测按钮何时被按下,因此响应UIControlEventTouchUpInside事件,我尝试了以下方法:Ios 子类UIButton并检测UIControlEventTouchUpInside,ios,objective-c,uibutton,Ios,Objective C,Uibutton,我尝试检测按钮何时被按下,因此响应UIControlEventTouchUpInside事件,我尝试了以下方法: - (void)setHighlighted:(BOOL)highlighted { if (highlighted) { self.titleLabel.textColor = [UIColor whiteColor]; [self.circleLayer setFillColor:self.color.CGColor]; }
- (void)setHighlighted:(BOOL)highlighted
{
if (highlighted)
{
self.titleLabel.textColor = [UIColor whiteColor];
[self.circleLayer setFillColor:self.color.CGColor];
}
else
{
[self.circleLayer setFillColor:[UIColor clearColor].CGColor];
self.titleLabel.textColor = self.color;
}
}
但只有当手指按在按钮上而没有松开时,如何在子类中检测触地内部动作?使用
UIControlEventTouchDown
而不是uicontroleventTouchInside
,因此当按钮按下时,它的动作方法将调用。您可以做的是在init方法中添加一个目标,并使用布尔值保持按钮状态:
在CustomButton.h中
@property(nonatomic,assign) BOOL selected;
在CustomButton.m中
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.selected = NO;
[self addTarget:self action:@selector(toggle:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (IBAction)toggle:(id)sender{
self.selected = !self.selected;
if (self.selected)
{
self.titleLabel.textColor = [UIColor whiteColor];
[self.circleLayer setFillColor:self.color.CGColor];
}
else
{
[self.circleLayer setFillColor:[UIColor clearColor].CGColor];
self.titleLabel.textColor = self.color;
}
}