gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:48:08 24 4
gpt4 key购买 nike

我收到错误:

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() 方法。

关于Swift NSLayoutConstraint 将 UIView 居中到兄弟的居中顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27497276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com