Skip to main content
 首页 » 操作系统

Swift NSLayoutConstraint 将 UIView 居中到兄弟的居中顶部

2024年01月01日42yxwkf

我收到错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Invalid pairing of layout attributes'

有什么想法吗?

这是我的代码:

static func addViewConstraintsCenterTop(constrainObject : UIView, toSibling : UIView) { 
 
    constrainObject.setTranslatesAutoresizingMaskIntoConstraints(false) 
 
    var constraints:[NSLayoutConstraint] = [] 
 
    var constW = NSLayoutConstraint(item: constrainObject, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: toSibling, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0) 
    constraints.append(constW) 
 
    var constH = NSLayoutConstraint(item: constrainObject, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: toSibling, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0) 
    constraints.append(constH) 
 
    constrainObject.addConstraints(constraints) 
} 

请您参考如下方法:

兄弟 View 之间的约束不能安装在任何一个兄弟上,但必须安装在共同的祖先上。

来自 Apple 的 Installing Constraints 部分 Auto Layout Guide :

The view that holds the constraint must be an ancestor of the views the constraint involves, and should usually be the closest common ancestor. (This is in the existing NSView API sense of the word ancestor, where a view is an ancestor of itself.) The constraint is interpreted in the coordinate system of that view.

如果你想保留这个约束,你需要保留对它的引用,并在你的 View 的父 View 改变时手动将它添加到正确的父 View ,最好是在你的 View Controller 的 updateViewConstraints() 方法。