Swift add constraint programmatically

后端 未结 5 1763
盖世英雄少女心
盖世英雄少女心 2021-01-31 08:23

I add a UILabel (amountLabel) in UIViewController in storyboard editor. And then in swift file, viewDidLoad, I programatically create a

相关标签:
5条回答
  • 2021-01-31 08:31
    let nameLabel: UILabel = {
    
       let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    

    if you forgot setting this label.translatesAutoresizingMaskIntoConstraints = false or if you add subview after constraints this problem arises

    0 讨论(0)
  • 2021-01-31 08:37

    I ran into the same problem that you described earlier. In order to make the programmatic subview, (in your case the paymentTextField) you have to add this to the subview first and then apply your constraints.

    By adding the subview to view first, this ensures both views have the same parent.

    0 讨论(0)
  • 2021-01-31 08:38

    Make sure you added the paymentTextField to your view:

    paymentTextField.translatesAutoResizingMaskIntoConstraints = false
    view.addSubview(paymentTextField)
    
    ...
    

    Add your constraints, for example paymentTextField.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true

    0 讨论(0)
  • 2021-01-31 08:41

    Checklist for this ISSUE:

    • Check whether you added the programmatically created view to its parent before activating constraints
    • Check whether you write constraints activation code inside viewDidLoad() / viewWillAppear(). You should write constraints activation code in updateViewConstraints or viewWillLayoutSubviews. ( suggested by vmeyer )
    • Check whether you turn off translatesAutoresizingMaskIntoConstraints.
    0 讨论(0)
  • 2021-01-31 08:44

    The error states that "because they have no common ancestor", which means that they don't share the same parent. In order to relate constraint between two items, they have to have a child-parent relationship or a sibling one.

    In your case just make sure they have the same parent view before adding the constraint programmatically.

    0 讨论(0)
提交回复
热议问题