首页 > 解决方案 > 在快速布局冲突中创建自定义按钮

问题描述

所以我尝试子类化 UIButton 来创建一个定制的按钮,确切地说是这样的 按钮示例

所以我遵循了互联网上的一些说明,因为那个人声明了框架而不是做

button.translatesAutoresizingMaskIntoConstraints = false

所以我试图“主动”对我的自定义按钮做这样的事情

class BigButton: UIButton {
    private let myTitleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.textAlignment = .center
        return label
    }()
    private let icon: UIImageView = {
        let icon = UIImageView()
        icon.contentMode = .scaleAspectFit
        return icon
    }()
    private var viewModel: MyCustomBigButton?
    override init(frame: CGRect) {
        self.viewModel = nil
        super.init(frame: frame)
    }
    init(with viewModel: MyCustomBigButton) {
        super.init(frame: .zero)
        self.viewModel = viewModel
        addSubview(myTitleLabel)
        addSubview(icon)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    public func configure(with viewModel: MyCustomBigButton) {
        myTitleLabel.text = viewModel.title
        icon.image = UIImage(named: viewModel.imageName)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        NSLayoutConstraint.activate([
            icon.topAnchor.constraint(equalTo: self.topAnchor, constant: 5),
            icon.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0),
            icon.heightAnchor.constraint(equalToConstant: frame.height*0.5),
            icon.widthAnchor.constraint(equalToConstant: frame.width*0.9),
            myTitleLabel.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 5),
            myTitleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0),
            myTitleLabel.widthAnchor.constraint(equalToConstant: frame.width*0.9),
            myTitleLabel.heightAnchor.constraint(equalToConstant: frame.height*0.2)
        ])
    }
}

将 NSlayout 添加到 UIButton 的子类,希望它可以工作,结果它与我为按钮设置的主布局冲突

class BerandaViewController: UIViewController {
    var didSendEventClosure: ((BerandaViewController.Event) -> Void)?
    let pesanButton: BigButton = {
        let button = BigButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .blue
        return button
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .purple
        view.addSubview(pesanButton)
        NSLayoutConstraint.activate([
            pesanButton.widthAnchor.constraint(equalToConstant: 200),
            pesanButton.heightAnchor.constraint(equalToConstant: 60),
            pesanButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            pesanButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

}

那么,我的代码有什么问题?还有其他参考资料可以让我学习如何正确构建它吗?谢谢

来自 swiftUI 让我错过了 swiftUI 创建自定义按钮的方式

标签: iosswiftuikit

解决方案


推荐阅读