关于ios:以编程方式设置按钮的宽度和高度

programmatically set a button width and height

我想以编程方式自定义UIButton。我的代码从这里开始:

1
2
3
4
5
6
7
8
class MyButton: UIButton {
    override func awakeFromNib() {
        super.awakeFromNib()

        layer.shadowRadius = 5.0
        ...
    }
}

现在我想为按钮定义一个恒定的宽度和高度,如何在代码中实现它?


我建议使用自动布局:

1
2
3
4
5
6
7
8
9
10
11
12
class MyButton: UIButton {
    override func awakeFromNib() {
        super.awakeFromNib()

        layer.shadowRadius = 5.0

        // autolayout solution
        self.translatesAutoresizingMaskIntoConstraints = false
        self.widthAnchor.constraint(equalToConstant: 200).isActive = true
        self.heightAnchor.constraint(equalToConstant: 35).isActive = true
    }
}


您需要重写override init(frame: CGRect)方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        // Set your code here

        let width = 300
        let height = 50
        self.frame.size = CGSize(width: width, height: height)

        backgroundColor = .red
        layer.shadowRadius = 5.0
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }    
}