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

Posted

技术标签:

【中文标题】我将 UIButton 子类化以创建自己的自定义按钮外观,但它不会重绘所有触摸事件【英文标题】:I am subclassing UIButton to create my own custom button look, however it is not redrawing on all touch events 【发布时间】:2013-03-09 15:43:46 【问题描述】:

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

我这样做是这样的: 在我的 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 但按钮的颜色未设置,它只是快速闪烁白色然后返回未选中颜色...

【问题讨论】:

【参考方案1】:

您可以尝试 UIView 的 highlighted 属性。

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

self.highlighted = YES;

反之亦然。

【讨论】:

【参考方案2】:

您可以尝试将 [self setNeedsDisplay] 从您的 touchesEnded:withEvent:touchesCancelled:withEvent: 方法中移出到您的 hesitateUpdate 方法中。

【讨论】:

恐怕没有解决问题......到目前为止我发现解决它的唯一方法是增加touchesEnded:withEvent:touchesCancelled:withEvent:的延迟时间

以上是关于我将 UIButton 子类化以创建自己的自定义按钮外观,但它不会重绘所有触摸事件的主要内容,如果未能解决你的问题,请参考以下文章

当我覆盖“drawRect”时,UIButton 样式设置被忽略

检测何时按下自定义 UIButton

UIButton 的自定义类视图

未调用自定义 UIButton 的 setIsSelected 方法

我的自定义 UIButton 不能用于替换 leftBarButtonItem

在主视图控制器的自定义单元格中使用来自 UIButton 的 IBAction