Centering a view in its superview using Visual Format Language

前端 未结 14 1343
天命终不由人
天命终不由人 2020-12-02 03:52

I just started learning AutoLayout for iOS and had a look at Visual Format Language.

It all works fine except for one thing: I just can\'t get a view to center withi

14条回答
  •  渐次进展
    2020-12-02 04:36

    I think it is better to manually create constraints.

    [superview addConstraint:
     [NSLayoutConstraint constraintWithItem:view
                                  attribute:NSLayoutAttributeCenterX
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superview
                                  attribute:NSLayoutAttributeCenterX
                                 multiplier:1
                                   constant:0]];
    [superview addConstraint:
     [NSLayoutConstraint constraintWithItem:view
                                  attribute:NSLayoutAttributeCenterY
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superview
                                  attribute:NSLayoutAttributeCenterY
                                 multiplier:1
                                   constant:0]];
    

    Now we can use NSLayoutAnchor to programatically define AutoLayout:

    (Available in iOS 9.0 and later)

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

    I recommend using SnapKit, which is a DSL to make Auto Layout easy on both iOS and macOS.

    view.snp.makeConstraints({ $0.center.equalToSuperview() })
    

提交回复
热议问题