[英]Ambiguous constraints when adding UILabel as subview to UITextView
The Problem问题
I have subclassed a UITextView
and added a UILabel
as a subview.我已经将
UITextView
子类化并添加了UILabel
作为子视图。 I want to position the label in the bottom right hand corner.我想将标签放在右下角。
Code代码
fileprivate lazy var counterLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
// add constraints
self.addConstraints([
NSLayoutConstraint(item: label, equalTo: self, attribute: .right),
NSLayoutConstraint(item: label, equalTo: self, attribute: .bottom)]
)
return label
}()
Screenshot截屏
As seen in the above screenshot, the red label is shown to have an ambiguous layout
如上图所示,红色标签显示
ambiguous layout
If I use a storyboard, and add the same two constraints (bottom, right) the label does not have an ambiguous position.如果我使用故事板,并添加相同的两个约束(底部,右侧),则标签的位置不会有歧义。 What have I done wrong?
我做错了什么?
What you want is a superview.你想要的是一个超级视图。 Add the label and the textview as subviews to this superview.
将标签和文本视图作为子视图添加到此超视图。
The problem may be because of instrict constraints.问题可能是由于严格的约束。 All labels has it's own constraints to expand due to text inside.
由于里面的文本,所有标签都有自己的扩展限制。 That constraints has some priority.
这种限制具有一定的优先性。 Possible problem may be that your created constraints have lower priority, which causes such problem.
可能的问题可能是您创建的约束具有较低的优先级,从而导致此类问题。 Try creating constraints with full function.
尝试创建具有完整功能的约束。 It works fine for me.
这对我来说可以。 Here is mine code with text field.
这是带有文本字段的我的代码。
self.leadingLabelConstraint = [NSLayoutConstraint constraintWithItem:_markLabel
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeading
multiplier:1.0 constant:0];
self.topLabelConstraint = [NSLayoutConstraint constraintWithItem:_markLabel
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1.0 constant:0];
[self.superview addConstraints:@[self.topLabelConstraint, self.leadingLabelConstraint]];
self.heightLabelConstraint = [NSLayoutConstraint constraintWithItem:_markLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:20];
[self.markLabel addConstraint:self.heightLabelConstraint];
self is - UITextField自我是 - UITextField
and markLabel is - UILabel.而markLabel 是- UILabel。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.