ios – 在UILabel上的constraint.constant发生更改后,父UIView没有调整大小

前端之家收集整理的这篇文章主要介绍了ios – 在UILabel上的constraint.constant发生更改后,父UIView没有调整大小前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
UPDATE

现在解决问题是当我更新bottomConstraint时,我将Constant设置为底部填充属性.听起来很合理但当然Constant应该设置为0 – BottomPadding.这就解释了为什么文本底部不可见,它被限制在剪切容器之外.

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

视图层次结构是

PaddedLabel – >的UILabel

当UILabel上的约束更新其常量时,外部视图不会达到高度.就好像外部UIView只看到标签的高度作为它需要的高度而不是标签的高度加上常量.这是它的外观

enter image description here

在UpdateConstraints中我添加了一些约束,如果有一个Text值,我将Constraint上的Constant设置为我想要填充的值,否则我将Constant设置为0.

public override void UpdateConstraints()
{
    base.UpdateConstraints();

    if (this.constraintsApplied == false)
    {
        this.leftConstraint = 
            NSLayoutConstraint.Create(this.NestedLabel,NSLayoutAttribute.Left,NSLayoutRelation.Equal,this,1.0f,this.LeftPadding);
        this.AddConstraint(this.leftConstraint);

        this.rightConstraint =
            NSLayoutConstraint.Create(this.NestedLabel,NSLayoutAttribute.Right,0 - this.RightPadding);
        this.AddConstraint(this.rightConstraint);

        this.topConstraint =
            NSLayoutConstraint.Create(this.NestedLabel,NSLayoutAttribute.Top,this.TopPadding);
        this.AddConstraint(this.topConstraint);

        this.bottomConstraint =
            NSLayoutConstraint.Create(this.NestedLabel,NSLayoutAttribute.Bottom,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();
    }
}

解决方法

如果希望PaddedLabel视图展开并适合UILabel内部,请更改底部约束.你想把PaddedLabel的底部绑在UILabel的底部,所以随着UILabel的增长,它会使PaddedLabel扩展!现在的样子,你告诉UILabel在PaddedLabel视图中挤压自己.

反转bottomConstraint,你应该设置.

猜你在找的iOS相关文章