我将UIButton子类化为创建我自己的自定义按钮外观,但它不会重绘所有触摸事件

时间:2013-03-09 15:43:47

标签: ios ios6 uibutton subclass

我正在尝试创建一个按钮子类,它为一个按钮(当它被选中时)着色,这取决于它是否是多项选择问题的正确答案。

我这样做是这样的: 在我的UIViewController中:

- (IBAction)answerQuestion:(id)sender {
    QGPrettyButton *answerButton;
    if ([sender isKindOfClass:[UIButton class]]) {
        answerButton = (QGPrettyButton *)sender;
        answerButton.isCorrectAnswer = [self.quizGame checkAnswer:self.currentQuestion answer:answerButton.titleLabel.text];
        [self performSelector:@selector(removeQuestion) withObject:nil afterDelay:TIME_TO_SHOW_CORRECT_ANSWER];
    }
}

在isCorrectAnswer的setter方法中:

- (void)setIsCorrectAnswer:(BOOL)isCorrectAnswer
{
    self.selected = YES;
    [self setNeedsDisplay];
    [self performSelector:@selector(returnToUnselected) withObject:nil afterDelay:TIME_TO_SHOW_CORRECT_ANSWER];
    _isCorrectAnswer = isCorrectAnswer;
}

- (void)returnToUnselected
{
    self.selected = NO;
    [self setNeedsDisplay];
}

在我的QGPrettyButton的绘制方法中:

CGFloat hue = UNSELECTED_HUE;
CGFloat saturation = UNSELECTED_SATURATION;

if (self.state == UIControlStateHighlighted) {
    hue = HOVERED_HUE;
    saturation = HOVERED_SATURATION;
}
if (self.state == UIControlStateSelected) {
    hue = self.isCorrectAnswer ? CORRECT_HUE : INCORRECT_HUE;
}

覆盖触摸:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    [self setNeedsDisplay];

}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    [self setNeedsDisplay];
    [self performSelector:@selector(hesitateUpdate) withObject:nil afterDelay:0.1];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [self setNeedsDisplay];
    [self performSelector:@selector(hesitateUpdate) withObject:nil afterDelay:0.1];
}

如果你按下按钮并再次释放,这一切都正常工作,但是如果你很快点击它就会调用IBAction,但是没有设置按钮的颜色,它只是快速闪烁白色然后再回到未选中状态颜色...

2 个答案:

答案 0 :(得分:0)

您可以尝试将[self setNeedsDisplay]移出touchesEnded:withEvent:touchesCancelled:withEvent:方法,然后转移到hesitateUpdate方法中。

答案 1 :(得分:0)

您可以尝试使用UIView的highlighted属性。

如果您希望突出显示,请执行以下操作:

self.highlighted = YES;

反之亦然。