如何使用新的UIButton配置方式在按钮上添加阴影?

How to add shadow on buttons with new UIButton Configuration way?

提问人:Martin Smith 提问时间:7/31/2023 最后编辑:Martin Smith 更新时间:8/1/2023 访问量:134

问:

我正在尝试重构应用程序中的按钮。以前,按钮上的阴影可以使用类似的属性轻松实现。但是,使用新的配置样式,我不确定如何在按钮上创建阴影。layer.shadowColor

我试图在谷歌上搜索解决方案,但不幸的是,我找不到任何解决方案。

public class MainButton: UIButton {

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup() {
    var config = UIButton.Configuration.borderedTinted()
    config.baseBackgroundColor = .red
    config.buttonSize = .medium
    config.cornerStyle = .capsule

    let handler: UIButton.ConfigurationUpdateHandler = { [self] button in
        switch button.state {
        case .highlighted:
            button.configuration?.baseBackgroundColor = .blue
        default:
            button.configuration?.baseBackgroundColor = .red
        }
    }

    config.titleTextAttributesTransformer =
    UIConfigurationTextAttributesTransformer { [self] incoming in
        var outgoing = incoming
        outgoing.font = UIFont().withSize(16)
        outgoing.foregroundColor = isEnabled ? .white : .gray
        return outgoing
    }

    config.contentInsets = .init(top: 4, leading: 4, bottom: 4, trailing: 4)
    configuration = config
    configurationUpdateHandler = handler
}

override var isEnabled: Bool {
    didSet {
        var updatedConfiguration = self.configuration
        updatedConfiguration?.background.backgroundColor = .clear
        self.configuration = updatedConfiguration
    }
}

}

Swift UIKIT UIBuint

评论

0赞 Sweeper 7/31/2023
中的属性仍然有效。这里到底有什么问题?shadowXXXCALayer
0赞 Chandaboy 7/31/2023
是的,sweeper 是对的,shadowColor 在所有配置状态下都有效。请用屏幕截图描述您的问题
0赞 Community 7/31/2023
请澄清您的具体问题或提供其他详细信息以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。
0赞 Martin Smith 8/1/2023
然后,如果我有这样一个 MainButton 类,那么有必要或足以向其添加类似 addShadow 的函数。我以为会有一个配置解决方案。func addShadow() { self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0, height: 1) self.layer.shadowOpacity = 0.2 }

答: 暂无答案