Programmatically Add CenterX/CenterY Constraints

前端 未结 7 764

I have a UITableViewController that doesn\'t display any sections if there is nothing to show. I\'ve added a label to indicate to the user that there is nothing to display w

7条回答
  •  孤街浪徒
    2020-11-29 18:44

    Center in container

    The code below does the same thing as centering in the Interface Builder.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // set up the view
        let myView = UIView()
        myView.backgroundColor = UIColor.blue
        myView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(myView)
    
        // Add code for one of the constraint methods below
        // ...
    }
    

    Method 1: Anchor Style

    myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    

    Method 2: NSLayoutConstraint Style

    NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true
    

    Notes

    • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
    • You will also need to add length and width constraints.
    • My full answer is here.

提交回复
热议问题