iOS开发笔记-123:swift5 UIButtonConfiguration

if #available(iOS 15.0, *) {
    // 初始化一个configuration,有多种方法,可根据需要选择
    btn.configuration = UIButton.Configuration.plain()
    // title 和 subtitle的对其关系,文本是上下排版的
    btn.configuration?.titleAlignment = .leading
    // title he subtitle的间距
    btn.configuration?.titlePadding = 16.scaleToScreen()
    // image 和 文本 的相对位置
    btn.configuration?.imagePlacement = .trailing
    // image 和 文本的间距
    btn.configuration?.imagePadding = 16.scaleToScreen()
    // button的内容(title,subtitle,image)显示后与按钮的边距,默认由一段距离
    btn.configuration?.contentInsets = NSDirectionalEdgeInsets.zero
    // 设置按钮的状态变化的监听,根据变化来改变按钮的显示内容,之前都是全部设置进去自动切换的,现在不行了
    btn.configurationUpdateHandler = {(button: UIButton) -> Void in
        //根据状态修改内容
        switch button.state {
        case .normal, .highlighted:
            // image变化
            button.configuration?.image = UIImage.arrowPickUp
            // 背景的变化,默认会有些自带效果,
            button.configuration?.background.backgroundColor = .clear
            // 字体的样式与之前一样
            button.configuration?.attributedTitle = AttributedString(title, attributes: AttributeContainer([
                NSAttributedString.Key.font : UIFont.customMediumFont(ofSize: UIFont.sizeL),
                NSAttributedString.Key.foregroundColor : UIColor.whiteAlpha50 ?? .red]))
            // 子标题,iOS15之后才有,对应的button.subtitleLabel
            button.configuration?.subtitle = "abc"

        case .selected, [.selected, .highlighted]:
            // image变化,与上面对应
            button.configuration?.image = UIImage.arrowUnfold

        case .disabled:
            Log.Debug(message: "不可\(btn.state)")
        default:
            Log.Debug(message: "默认值\(btn.state)")
        }
        button.updateConfiguration()
        
    }
} else {
    // iOS15 之前的属性设置
    btn.setTitle(title, for: .normal)
    // 字体颜色
    btn.setTitleColor(UIColor.whiteAlpha50, for: .normal)
    btn.setTitleColor(UIColor.whiteAlpha50, for: .selected)
    // 设置图片各种状态都需要设置
    btn.setImage(UIImage.arrowUnfold, for: .normal)
    btn.setImage(UIImage.arrowUnfold, for: .highlighted)
    btn.setImage(UIImage.arrowPickUp, for: .selected)
    btn.setImage(UIImage.arrowPickUp, for: [.selected, .highlighted])
    btn.titleLabel?.font = UIFont.customFont(ofSize: UIFont.sizeL)
    // 改变title与image的位置关系
    btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -15.scaleToScreen(), bottom: 0, right: 15.scaleToScreen())
    btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 51.scaleToScreen(), bottom: 0, right: -51.scaleToScreen())
    btn.backgroundColor = .gray
}

你可能感兴趣的:(iOS开发笔记-123:swift5 UIButtonConfiguration)