父级 UIView 在 UILabel 约束常量更改后未重新调整大小

4

更新

问题已解决,问题在于当我更新bottomConstraint时,我将Constant设置为底部填充属性。听起来很合理,但当然Constant应该被设置为0-BottomPadding。这就解释了为什么文本底部看不见,因为它被限制在其剪辑容器之外。

我有一个简单的UIView自定义控件叫做PaddedLabel,它包装(而不是继承)一个UILabel

视图层次结构为

PaddedLabel -> UILabel

当UILabel上的约束常量更新时,外部视图的高度不会改变。就好像外部UIView只看到标签的高度作为所需的高度,而不是标签高度加上常量。效果如下图所示:

enter image description here

在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();
    }
}

更新约束应该用于添加缺失的约束,而不是修改它们的值。尝试使用实际设置你想要用于约束的常量来替换this.SetNeedsUpdateConstraints(); 然后调用set needs layout和layout if needed。 - JackRobinson
这是我之前尝试过的事情,如果在视图的初始加载期间分配文本,则可以正常工作。但是,如果在视图加载后分配文本,例如作为后台进程的结果,那么问题就一样了。 - Pat Long - Munkii Yebee
1个回答

0
如果您想让PaddedLabel视图扩展并适应内部的UILabel,请更改底部约束。您希望将PaddedLabel的底部与UILabel的底部绑定,因此随着UILabel的增长,它会使PaddedLabel扩展!现在的方式是,您告诉UILabel将自己挤压在PaddedLabel视图内部。
反转bottomConstraint,然后您就可以设置了。

有趣,我现在会尝试一下。然而,当文本没有在后台加载时,当前的限制条件运行良好... - Pat Long - Munkii Yebee
好的,我已经修复了。这是我自己的极度愚蠢。问题已更新。 - Pat Long - Munkii Yebee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接