UIButton 按下后挪开仍处于选中状态的问题

UIButton 按下后挪开仍处于选中状态的问题_第1张图片
bug问题效果.gif

Bug描述

  • 如上图,按下按键的时候如果不松开,同时挪动到别处,按键仍处于按下状态。
  • 效果的实现方式是通过代码 addTarget来做的
[self.InsideBtn addTarget:self action:@selector(BtnPressdownEffect:) forControlEvents:UIControlEventTouchDown];
[self.InsideBtn addTarget:self action:@selector(SendBtnValueToScreen:) forControlEvents:UIControlEventTouchUpInside];
  • 很多工程中不是通过代码addtarget添加,可以通过 XIB/storyboard中的选中效果来实现按下后的状态变更。
    UIButton 按下后挪开仍处于选中状态的问题_第2张图片
    示意图

    同时时间也是用下面这个方式来做,并没有告知时间是touchupside还是down
-(IBAction)salesSlip:(id)sender

Bug发生原因及解决方法

问题原因:

  • 原先的想法是利用 addTarget来添加按键效果。但是事实发现,对于 forControlEvents来添加案件效果,就会出现上图中的bug.
  • 结论:改变按键的背景,不能通过修改backgroundColor来实现。我们通过XIB/Storyboard去修改的时候也发现不可能不同按键条件下利用更改backgroundColor来实现效果。
  • 唯一的方式是利用更改背景图片来实现按键效果。

解决方式:

通过设定[setBackgroundImage:... forState:...]

  • 按下状态为 UIControlStateHighlighted
  • 正常状态为 UIControlStateNormal
// 按键按下之前的背景和字体风格
    UIFont *MyFont = [UIFont fontWithName:@"Geeza Pro"//@"DB LCD Temp"
                                     size:(self.InsideBtn.isFunctionBtn)?25:30];
    NSAttributedString* MyPrefferText = [[NSAttributedString alloc] initWithString:self.InsideBtn.ButtonValue
                                                                        attributes:@{NSFontAttributeName:MyFont,
                                                                          NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [btn setAttributedTitle:MyPrefferText
                   forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:( (self.InsideBtn.isFunctionBtn)?@"功能按键背景":@"普通按键背景" )] forState:UIControlStateNormal];
    
    // 按键按下之后的背景和字体风格
    MyFont        = [UIFont fontWithName:@"Geeza Pro"//@"DB LCD Temp"
                                    size:(self.InsideBtn.isFunctionBtn)?30:40];
    MyPrefferText = [[NSAttributedString alloc] initWithString:self.InsideBtn.ButtonValue
                                                    attributes:@{NSStrokeColorAttributeName:[UIColor blackColor],
                                                                 NSFontAttributeName:MyFont,
                                                                 NSForegroundColorAttributeName:[UIColor darkGrayColor]}];
    
    [btn setAttributedTitle:MyPrefferText
                   forState:UIControlStateHighlighted];
    [btn setBackgroundImage:[UIImage imageNamed:@"按键按下背景"] forState:UIControlStateHighlighted];

你可能感兴趣的:(UIButton 按下后挪开仍处于选中状态的问题)