Set the center of a UIButton programmatically - SWIFT

后端 未结 5 1491
孤街浪徒
孤街浪徒 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:48

    This approach is using Using NSLayoutConstraint where self.cenBut is the IBoutlet for your button.

    func setupConstraints() {
        let centerX = NSLayoutConstraint(item: self.cenBut, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
        let centerY = NSLayoutConstraint(item: self.cenBut, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
        let height = NSLayoutConstraint(item: self.cenBut, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 22)
        self.cenBut.translatesAutoresizingMaskIntoConstraints = false
        self.view.addConstraints([centerX, centerY, height])
    }
    

    In viewDidLoad()

    self.view.removeConstraints(self.view.constraints)
    self.setupConstraints()
    

提交回复
热议问题