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的切換,這個效果還是很糟糕的。
解決方法
可以使用UIButtonTypeCustom的button,自定義button在設置title的時候,是立即生效的,無動畫過程。缺點是,你需要自己去實現按鈕按下效果。按下效果推薦重寫setHighLight的方法去實現,如果使用touch事件實現的話,在tableView的BounceVertical過程中,會只響應touchDown事件,而不響應touchUp事件(這個現象的原因有待研究,猜測和runloop機制有關)
-
取消系統button的設置動畫,參考How to stop unwanted UIButton animation on title change?
[UIView performWithoutAnimation:^{ [myButton setTitle:text forState:UIControlStateNormal]; [myButton layoutIfNeeded]; }];