简体   繁体   中英

Adding constraints programmatically is not respecting priority

The below is in a loop which adds views to a superview. Each subview is the remove button and information to the left.....they are sitting in a parent view...

Each subview is constrained to the view above...and the top view is constrained to the top edge of the parent view..all added programatically.

The remove button will delete one at a time

我不添加次要优先级800最高锚点的精细版本

Once I add a secondary top constraint to each view to account for the deleting then I get the following....

在此处输入图片说明

var horizontalConstraint1 = NSLayoutConstraint()
var horizontalConstraint2 = NSLayoutConstraint()
var verticalConstraint1 = NSLayoutConstraint()
var verticalConstraintOuter = NSLayoutConstraint()

    horizontalConstraint1 = v.leadingAnchor.constraint(equalTo: (v.superview?.leadingAnchor)!,constant:10)
    horizontalConstraint2 = v.trailingAnchor.constraint(equalTo: (v.superview?.trailingAnchor)!,constant:-10)
      if self.prevView == nil{
           verticalConstraint1 = v.topAnchor.constraint(equalTo: (v.superview?.topAnchor)!, constant: 0)
           NSLayoutConstraint.activate([horizontalConstraint1,horizontalConstraint2,verticalConstraint1 ]) 
            }else {
                 if let pv = self.prevView as? UIView {
                  verticalConstraint1 = v.topAnchor.constraint(equalTo: (pv.bottomAnchor), constant: 10)
                  verticalConstraintOuter = v.topAnchor.constraint(equalTo: (v.superview?.topAnchor)!,constant:10 )
                  verticalConstraintOuter.priority = UILayoutPriority(rawValue: 800)
                  NSLayoutConstraint.activate([horizontalConstraint1,horizontalConstraint2,verticalConstraint1,verticalConstraintOuter])
                        }
     }
       self.prevView = v 

Your technique is wrong. You do not add a "secondary top constraint to each view to account for the deleting". When you remove a view, you completely remove the existing constraints and create a whole new set of constraints.

Alternatively, use UIStackView, which does the work for you: you set an arranged view's isHidden to true and the stack view rewrites the constraints of its arranged views.

In your case, an even simpler technique would be to make your interface be a UITableView. Now all you have to do is remove a row of the table. The notion of "delete this row" is basically built into a table view; you get it almost for free (including a Delete button, though no law says you have to use that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM