I would like to programmatically customize the UIButton
. My code starts here:
class MyButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
layer.shadowRadius = 5.0
...
}
}
Now I would like to define a constant width and height for the button, how to do it in code?
I would recommend to use autolayout:
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
}
}
You need to override override init(frame: CGRect)
method
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With