[英]Change relation of NSLayoutConstraint programmatically in iOS
I have a UITextView
at the bottom of screen.我在屏幕底部有一个
UITextView
。
It has leading, trailing bottom space constraints to the superview
.它对
leading, trailing bottom space constraints to the superview
具有leading, trailing bottom space constraints to the superview
。
It has also height constraint with value (constant) 40
.它还具有
height constraint with value (constant) 40
。
I want to make this text view of flexible height as I go on typing more text in it.当我继续在其中输入更多文本时,我想让这个文本视图具有灵活的高度。 I can make flexible height by changing height constraint value to
greater than or equal
to as:我可以通过将高度约束值更改为
greater than or equal
来制作灵活的高度:
It works fine and text view height goes on increasing.它工作正常,文本视图高度不断增加。
But when I make it, storyboard show this error:但是当我制作它时,情节提要显示此错误:
I want to make constraint value greater than or equal to programmatically, not from storyboard.我想以编程方式使约束值大于或等于,而不是来自故事板。
I know that there is one property of NSLayoutConstraint
called我知道
NSLayoutConstraint
有一个属性叫做
public var relation: NSLayoutRelation { get }
but as we can see it is readonly.但正如我们所见,它是只读的。
How can I change this relation to one of:如何将这种关系更改为以下关系之一:
public enum NSLayoutRelation : Int {
case LessThanOrEqual
case Equal
case GreaterThanOrEqual
}
Or is there any workaround make a view of flexible height in auto-layout based storyboard?或者是否有任何解决方法可以在基于自动布局的故事板中查看灵活的高度?
I know about making IBOutlet of constraint and changing it's constant value, but in my situation I can not do this, it should be changed dynamically.我知道如何制作约束的 IBOutlet 并更改它的常量值,但在我的情况下我不能这样做,它应该动态更改。
Related to: auto layout modify multiplier of constriaint programmatically相关: 自动布局以编程方式修改约束的乘数
With ARC:使用 ARC:
- (void)changeConstraintRelationToEqual:(NSLayoutConstraint * __strong *)constraint{
NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:(*constraint).firstItem attribute:(*constraint).firstAttribute relatedBy:NSLayoutRelationEqual toItem:(*constraint).secondItem attribute:(*constraint).secondAttribute multiplier:(*constraint).multiplier constant:(*constraint).constant];
[self.view removeConstraint:(*constraint)];
[self.view addConstraint:newConstraint];
*constraint = newConstraint;
}
我过去解决了这个问题,方法是在接口构建器中将我需要在运行时设置的约束标记为“占位符 - 在构建时删除”,然后通过代码添加约束以编程方式提供基于动态值的约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.