Set the center of a UIButton programmatically - SWIFT

后端 未结 5 1497
孤街浪徒
孤街浪徒 2021-02-19 11:22

I have a UIButton inside a UIView, my UIButton has constraints which I set in storyboard. Now, I want to set the center of the UIBut

5条回答
  •  耶瑟儿~
    2021-02-19 11:46

    since you are using constraints, you won't be able to set the center so you need to use constraints to set the center as well:

        let centerYCon = NSLayoutConstraint(item: labelMessage,
            attribute: .CenterY,
            relatedBy: .Equal,
            toItem: contentView,
            attribute: .CenterY,
            multiplier: 1.0,
            constant: 0.0);
        contentView.addConstraint(centerYCon);
    
    
        let centerXCon = NSLayoutConstraint(item: labelMessage,
            attribute: .CenterX,
            relatedBy: .Equal,
            toItem: contentView,
            attribute: .CenterX,
            multiplier: 1.0,
            constant: 0.0);
        contentView.addConstraint(centerXCon);
    

    I'm assuming that you know what "programmatically" means with autolayout constraints. If you are truly using autolayout then you must have set the properties of your button to setTranslatesAutoresizingMaskIntoConstraints to false.

提交回复
热议问题