更新
问题已解决,问题在于当我更新bottomConstraint
时,我将Constant
设置为底部填充属性。听起来很合理,但当然Constant
应该被设置为0-BottomPadding
。这就解释了为什么文本底部看不见,因为它被限制在其剪辑容器之外。
我有一个简单的UIView自定义控件叫做PaddedLabel,它包装(而不是继承)一个UILabel
视图层次结构为
PaddedLabel -> UILabel
当UILabel上的约束常量更新时,外部视图的高度不会改变。就好像外部UIView只看到标签的高度作为所需的高度,而不是标签高度加上常量。效果如下图所示:
在UpdateConstraints中,我添加了一些约束,如果有文本值,我将约束上的Constant设置为所需的填充值,否则我将Constant设置为0。
public override void UpdateConstraints()
{
base.UpdateConstraints();
if (this.constraintsApplied == false)
{
this.leftConstraint =
NSLayoutConstraint.Create(this.NestedLabel, NSLayoutAttribute.Left, NSLayoutRelation.Equal, this, NSLayoutAttribute.Left, 1.0f, this.LeftPadding);
this.AddConstraint(this.leftConstraint);
this.rightConstraint =
NSLayoutConstraint.Create(this.NestedLabel, NSLayoutAttribute.Right, NSLayoutRelation.Equal, this, NSLayoutAttribute.Right, 1.0f, 0 - this.RightPadding);
this.AddConstraint(this.rightConstraint);
this.topConstraint =
NSLayoutConstraint.Create(this.NestedLabel, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1.0f, this.TopPadding);
this.AddConstraint(this.topConstraint);
this.bottomConstraint =
NSLayoutConstraint.Create(this.NestedLabel, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, this, NSLayoutAttribute.Bottom, 1.0f, 0 - this.BottomPadding);
this.AddConstraint(this.bottomConstraint);
this.constraintsApplied = true;
}
if (this.Text.HasValue())
{
this.topConstraint.Constant = this.TopPadding;
// The following code was the problem.
// It should have been 0 - this.BottomPadding Now corrected
// this.bottomConstraint.Constant = this.BottomPadding;</del>
this.bottomConstraint.Constant = 0 - this.BottomPadding;
}
else
{
this.topConstraint.Constant = 0;
this.bottomConstraint.Constant = 0;
}
}
当设置 Text 属性时,我会在内部的 UILabel 上设置 Text 属性并调用 SetNeedsUpdateConstraints 方法。
public string Text
{
get
{
return this.text;
}
set
{
if (this.text == value)
{
return;
}
this.text = value;
this.nestedLabel.Text = value;
this.SetNeedsUpdateConstraints();
}
}