简体   繁体   中英

How to resize a view to fit a label subview using auto layout?

I'm trying to make a translucent black rectangle with some text in it, to convey some info to users. It seems to work, but when the phone's text size is large then the label's contents are cut off -- the view won't expand its dimensions.

To create this I added a UIView with a black background and rounded corners, made it somewhat transparent, and placed a UILabel inside it. Constraints on the view should allow it to grow wider when the phone is rotated, and constraints on the label keep its edges pinned to the view.

Here are the view's constraints:

Align Center X to: Superview
Align Center Y to: Superview
Trailing Space to: Superview >= 40
Leading Space to: Superview >= 40
Width >= 200
Width <= 300
Height >= 100
Height <= 150

And the label's constraints:

Trailing Space to: Superview Equals:Default
Leading Space to: Superview Equals:Default
Bottom Space to: Superview Equals:Default
Top Space to: Superview Equals:Default

When run on an iPhone 5, the view's size is 200 x 102 for some reason and the text is truncated, even though its constraints allow it to go up to 300 x 150. What am I doing wrong?

Just set UILabel Top/Bottom/Lidding/Trailing constraints to zero because it has intrinsic content size. It means label will wish to become that wide to contain its string value all visible. Look at this article

Create constraint programmatically

_constraint=[NSLayoutConstraint constraintWith...];
[self.view addConstraint:_constraint];
//...
_constraint.constant=40;

Use outlet if all the constraints are defined in IB. Just connect it to your constraint.

@property (nonatomic,weak) IBOutlet NSLayoutConstraint *constraint;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM