Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically set a button width and height

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?

like image 550
Leem.fin Avatar asked Sep 07 '17 11:09

Leem.fin


2 Answers

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
    }
} 
like image 50
Milan Nosáľ Avatar answered Sep 28 '22 06:09

Milan Nosáľ


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")
    }    
}
like image 43
Govaadiyo Avatar answered Sep 28 '22 07:09

Govaadiyo