iOS15引入了UIButton.Configuration,将视图的配置标签独立出来了,我们来看下常用的配置都有哪些吧
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)
//这儿构建button configuration有几种效果(plain/tinted/gray/filled...),可自己试
var btnConfig = UIButton.Configuration.plain()
//设置按钮title和subtitle之间主title方位
btnConfig.titleAlignment = .trailing
//设置按钮title和subtitle间距
btnConfig.titlePadding = 20
//设置title的字体文字等
btnConfig.attributedTitle = AttributedString("ABCD",attributes: AttributeContainer([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 30),NSAttributedString.Key.foregroundColor:UIColor.red]))
//设置subtitle的字体文字等
btnConfig.attributedSubtitle = AttributedString("EF",attributes: AttributeContainer([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 20),NSAttributedString.Key.foregroundColor:UIColor.green]))
//设置图片
btnConfig.image = UIImage.checkmark
//设置图片和主title之间图片的方位
btnConfig.imagePlacement = .top
//设置图片和主title间距
btnConfig.imagePadding = 20
//设置包含图片/主titie/subtitle内容后的与按钮边界的距离
btnConfig.contentInsets = NSDirectionalEdgeInsets.zero
//设置菊花,菊花和图片优先级:菊花>图片,所以同时设置,只看到菊花
btnConfig.showsActivityIndicator = true
btnConfig.activityIndicatorColorTransformer = UIConfigurationColorTransformer.grayscale
//监听按钮状态,这儿不用调用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的注释就可知道这是一个需要我们主动调用并立即更新UI的,例如,我们切换了视图,需要更新按钮UI,就可以主动调用且注释也写了按钮状态改变不用调用此API,它会自动调用。
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的我们自定义的子类才需要调用此API