美文网首页
UIButtonTypeSystem遇到的坑

UIButtonTypeSystem遇到的坑

作者: angry_zxy | 来源:发表于2018-11-07 11:03 被阅读0次

    UIButtonType

    UIButton提供了buttonWithType的类方法来初始化,UIButtonType是一个枚举:

    typedef NS_ENUM(NSInteger, UIButtonType) {
        UIButtonTypeCustom = 0,                         // no button type
        UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  // standard system button
    
        UIButtonTypeDetailDisclosure,
        UIButtonTypeInfoLight,
        UIButtonTypeInfoDark,
        UIButtonTypeContactAdd,
    
        UIButtonTypePlain API_AVAILABLE(tvos(11.0)) API_UNAVAILABLE(ios, watchos), // standard system button without the blurred background view
    
        UIButtonTypeRoundedRect = UIButtonTypeSystem   // Deprecated, use UIButtonTypeSystem instead
    };
    

    平时用的比较多的是UIButtonTypeCustom和UIButtonTypeSystem,其中UIButtonTypeCustom和[[UIButton alloc] init]都是自定义的button,目前使用起来感觉是一样的(此处不严谨,后续有新的发现再完善)。UIButtonTypeSystem是创建系统的button,系统button内做了一些处理,比如highlight时透明度为0.3,设置title的时候有动画效果。一般情况下,使用系统button可以很省事。

    遇到的问题

    系统button在设置title的时候是有一个动画效果的,在真机iPhone7p上测试动画效果大约是170ms,也就是说,当调用了setTitle设置后,需要170ms后才会真的设置,表现地效果就是文字淡入淡出的效果,这样似乎也没什么问题。当时当button本身有一个textA,然后再去修改为textB就会看到textA -> textB的切换。假设有一个tableView,复用的cell上有button,button的文字不是一样的。那么在reload的时候,就会出现cell的文字出现textA -> textB的切换,这个效果还是很糟糕的。

    解决方法

    1. 可以使用UIButtonTypeCustom的button,自定义button在设置title的时候,是立即生效的,无动画过程。缺点是,你需要自己去实现按钮按下效果。按下效果推荐重写setHighLight的方法去实现,如果使用touch事件实现的话,在tableView的BounceVertical过程中,会只响应touchDown事件,而不响应touchUp事件(这个现象的原因有待研究,猜测和runloop机制有关)

    2. 取消系统button的设置动画,参考How to stop unwanted UIButton animation on title change?

      [UIView performWithoutAnimation:^{
          [myButton setTitle:text forState:UIControlStateNormal];
          [myButton layoutIfNeeded];
      }];
      

    相关文章

      网友评论

          本文标题:UIButtonTypeSystem遇到的坑

          本文链接:https://www.haomeiwen.com/subject/lupmxqtx.html