gpt4 book ai didi

iphone - 如何以编程方式在 UIButton 之间获取 NSLayoutConstraint?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:56 25 4
gpt4 key购买 nike

在一个 View 中,我正在插入一个新的 UIButton,因为我一直在使用 AutoLayout,所以我需要获得要在其下方插入按钮的 View 的约束。如何以编程方式获取 NSLayoutConstraint,以便我可以删除旧约束,然后创建新约束。谢谢。

编辑:enter image description here

引用图,我需要在B1和B2之间插入B3,所以我需要删除B1和B2之间已经设置的固定空间约束,我需要将B3底部连接到B2的顶部,B3的顶部连接到B1的底部.

最佳答案

I need to delete the already set fixed space constraint between B1 and B2

以编程方式查找约束

您可以在 View 约束中搜索 B1,或者在创建它时保留对 NSLayoutConstraint 的引用。搜索 B1 的约束可能效率较低:所有关系约束( View 到另一个 View )都是封闭 superview 的一部分。假设您有 B1 的句柄,您可以在其父 View 中列出所有 B1 约束,如下所示:

// Searching all relationship constraints involving b1
for item in self.view.constraints() {
if let constraint = item as? NSLayoutConstraint {
if let button = constraint.firstItem as? UIButton {
if button == b1 {
println("firstItem found: \(constraint)")
}
}
if let button = constraint.secondItem as? UIButton {
if button == b1 {
println("secondItem found: \(constraint)")
}
}
}
}

记住约束

到目前为止,更简洁的方法是保留对您以后要修改或删除的 NSLayoutConstraint 的引用。要在 Storyboard 中执行此操作,请创建您需要的约束。

enter image description here

然后按住 Control 键将引用直接拖到您的源文件中,以便稍后对其进行操作。

enter image description here

关于iphone - 如何以编程方式在 UIButton 之间获取 NSLayoutConstraint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17566650/

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