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,目前使用起來感覺是一樣的(此處不嚴謹,后續(xù)有新的發(fā)現(xiàn)再完善)。UIButtonTypeSystem是創(chuàng)建系統(tǒng)的button,系統(tǒng)button內(nèi)做了一些處理,比如highlight時透明度為0.3,設(shè)置title的時候有動畫效果。一般情況下,使用系統(tǒng)button可以很省事。
遇到的問題
系統(tǒng)button在設(shè)置title的時候是有一個動畫效果的,在真機iPhone7p上測試動畫效果大約是170ms,也就是說,當(dāng)調(diào)用了setTitle設(shè)置后,需要170ms后才會真的設(shè)置,表現(xiàn)地效果就是文字淡入淡出的效果,這樣似乎也沒什么問題。當(dāng)時當(dāng)button本身有一個textA,然后再去修改為textB就會看到textA -> textB的切換。假設(shè)有一個tableView,復(fù)用的cell上有button,button的文字不是一樣的。那么在reload的時候,就會出現(xiàn)cell的文字出現(xiàn)textA -> textB的切換,這個效果還是很糟糕的。
解決方法
可以使用UIButtonTypeCustom的button,自定義button在設(shè)置title的時候,是立即生效的,無動畫過程。缺點是,你需要自己去實現(xiàn)按鈕按下效果。按下效果推薦重寫setHighLight的方法去實現(xiàn),如果使用touch事件實現(xiàn)的話,在tableView的BounceVertical過程中,會只響應(yīng)touchDown事件,而不響應(yīng)touchUp事件(這個現(xiàn)象的原因有待研究,猜測和runloop機制有關(guān))
-
取消系統(tǒng)button的設(shè)置動畫,參考How to stop unwanted UIButton animation on title change?
[UIView performWithoutAnimation:^{ [myButton setTitle:text forState:UIControlStateNormal]; [myButton layoutIfNeeded]; }];