iOS15引入了UIButton.Configuration瑟押,將視圖的配置標(biāo)簽獨立出來了饭于,我們來看下常用的配置都有哪些吧
let btn = UIButton(type: .custom)
btn.backgroundColor = .gray
btn.frame.size = CGSizeMake(200, 150)
btn.center = view.center
btn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchDown)
//這兒構(gòu)建button configuration有幾種效果(plain/tinted/gray/filled...),可自己試
var btnConfig = UIButton.Configuration.plain()
//設(shè)置按鈕title和subtitle之間主title方位
btnConfig.titleAlignment = .trailing
//設(shè)置按鈕title和subtitle間距
btnConfig.titlePadding = 20
//設(shè)置title的字體文字等
btnConfig.attributedTitle = AttributedString("ABCD",attributes: AttributeContainer([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 30),NSAttributedString.Key.foregroundColor:UIColor.red]))
//設(shè)置subtitle的字體文字等
btnConfig.attributedSubtitle = AttributedString("EF",attributes: AttributeContainer([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 20),NSAttributedString.Key.foregroundColor:UIColor.green]))
//設(shè)置圖片
btnConfig.image = UIImage.checkmark
//設(shè)置圖片和主title之間圖片的方位
btnConfig.imagePlacement = .top
//設(shè)置圖片和主title間距
btnConfig.imagePadding = 20
//設(shè)置包含圖片/主titie/subtitle內(nèi)容后的與按鈕邊界的距離
btnConfig.contentInsets = NSDirectionalEdgeInsets.zero
//設(shè)置菊花维蒙,菊花和圖片優(yōu)先級:菊花>圖片镰绎,所以同時設(shè)置,只看到菊花
btnConfig.showsActivityIndicator = true
btnConfig.activityIndicatorColorTransformer = UIConfigurationColorTransformer.grayscale
//監(jiān)聽按鈕狀態(tài)木西,這兒不用調(diào)用setNeedsUpdateConfiguration或updateConfiguration
btn.configurationUpdateHandler = { button in
switch button.state {
case .normal,.highlighted:
button.configuration?.image = UIImage.add
case .selected:
button.configuration?.image = UIImage.remove
default:
break
}
}
btn.configuration = btnConfig
view.addSubview(btn)
這里說下setNeedsUpdateConfiguration
和updateConfiguration
這兩個更新方法
setNeedsUpdateConfiguration
/// Requests the view update its configuration for its current state. This method is called automatically when the button's state may have changed, as well as in other circumstances where an update may be required. Multiple requests may be coalesced into a single update at the appropriate time.
@available(iOS 15.0, *)
open func setNeedsUpdateConfiguration()
- 從API的注釋就可知道這是一個需要我們主動調(diào)用并立即更新UI的畴栖,例如,我們切換了視圖八千,需要更新按鈕UI吗讶,就可以主動調(diào)用且注釋也寫了按鈕狀態(tài)改變不用調(diào)用此API,它會自動調(diào)用恋捆。
updateConfiguration
/// Subclasses should override this method and update the button's configuration. This method should not be called directly, use setNeedsUpdateConfiguration to request an update.
@available(iOS 15.0, *)
open func updateConfiguration()
- 從注釋我們知道照皆,只有UIButton的我們自定義的子類才需要調(diào)用此API