简体   繁体   English

如何删除以编程方式添加的约束

[英]How to remove constraint that is added programmatically

How to remove this constraint programmatically. 如何以编程方式消除此约束。 please help 请帮忙

cell.textView.addConstraint(NSLayoutConstraint(item: cell.textView, attribute: .height, relatedBy: .greaterThanOrEqual,
                                                           toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 54))

that code is added in tablecells .i want to remove when keyboard hide. 该代码已添加到tablecell中。我想在隐藏键盘时删除该代码。

So it seems you want to remove just this one constraint, without interfering with default ones. 因此,似乎您只想删除这一约束,而不干扰默认约束。 The simplest way would be, of course, to just keep a reference to this constraint and to disable it. 当然,最简单的方法是仅保留对此约束的引用并禁用它。

let constraint = NSLayoutConstraint(item: cell.textView, 
                               attribute: .height, 
                               relatedBy: .greaterThanOrEqual, 
                                  toItem: nil, 
                               attribute: .notAnAttribute,
                              multiplier: 1.0, constant: 54)
cell.textView.addConstraint(constraint)
strongReferenceToConstraint = constraint

/// somewhere else 

cell.textView.removeConstraint(strongReferenceToConstraint)

But if you can't keep reference to it, or for some reason it's not accessible to you, you can try iterating over all constraints of this view and finding the one on height by checking its firstAttribute property 但是,如果您不能继续引用它,或者由于某种原因而无法访问它,则可以尝试遍历此视图的所有约束并通过检查其firstAttribute属性来找到一个在heightfirstAttribute

for constraint in cell.textView.constraints
{
    if constraint.firstAttribute == .height
    {
        constraint.isActive = false
        break
    }
}
var constraint = NSLayoutConstraint(item: cell.textView, attribute: .height, relatedBy: .greaterThanOrEqual,
                                                           toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 54)

constraint.isActive = false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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