Set UIView size to fit subViews

后端 未结 2 1563
难免孤独
难免孤独 2020-12-31 03:31

I\'m having a UIView that\'s containing two UILabels, which have dynamic heights. I want the UIView to fit the size of the UILabels + some padding.

2条回答
  •  一向
    一向 (楼主)
    2020-12-31 04:12

    @Girish M answer is correct. Just to clarify. Set the top label's constraint to the views' top, vertical spacing between the two labels and a bottom constraint between the bottom label and UIView. Do not set any height constraints.

    Alternatively, if you want a bit more control over the heights of the UILabels, you can add height constraints in storyboard for the labels and create outlets for them in your code. Perform this code when changing the text of the labels.

        label1.sizeToFit()
        label2.sizeToFit()
    
        label1HeightConstraint.constant = label1.frame.size.height
        label2HeightConstraint.constant = label2.frame.size.height
    
        view.layoutSubviews()
    

提交回复
热议问题