Parent UIView not resizing after constraint.constant on UILabel changed

I have a simple UIView custom control called PaddedLabel that wraps (not inherits) a UILabel

The view hierarchy is

PaddedLabel -> UILabel

When the constraints on the UILabel have their constants updated the outer View does not chnage height. It is as if the outer UIView is seeing only the Height of the Label as the Height it needs rather than the Height of the Label plus constants. This is how it looks

enter image description here

In UpdateConstraints I add some constraints and if there is a Text value I set the Constant on the Constraint to the value I want for padding else I set the Constant to 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;
        this.bottomConstraint.Constant = this.BottomPadding;
    }
    else
    {
        this.topConstraint.Constant = 0;
        this.bottomConstraint.Constant = 0;
    }
}

When the Text property is set I set the Text property on the inner UILabel and call SetNeedsUpdateConstraints

public string Text
{
    get
    {
        return this.text;
    }

    set
    {
        if (this.text == value)
        {
            return;
        }

        this.text = value;
        this.nestedLabel.Text = value;
        this.SetNeedsUpdateConstraints();
    }
}


Source: ios

Leave a Reply