简体   繁体   中英

Show background color in UILabel only as long as the text is

I've set the backgroundColor via the attributes tab for the view controller in my Storyboard. But I want to show the background color only in the length of the text which is filled into the label, not in the whole possible length.

I can not attach any image, so here is what I would like to have:

Try the following steps:

  1. Select the UILabel in the Storyboard.
  2. Open the "Size Inspector."
  3. In the "Label" section, make sure "Explicit" is unchecked.
  4. In the list of "Constraints," make sure that no constraint provides a value for the width property. Also, remove any constraints that pin the right edge of the UILabel to the UIImageView as this will implicitly give Auto Layout a fixed width for the label.
  5. Add an "Equal Widths" constraint between the UILabel and the UIImageView . This can be achieved by control-dragging from the label to the image view in the Storyboard and selecting "Equal Widths" from the menu that appears.
  6. Select either the label of the image view. Open the "Size Inspector" again double click on the box that corresponds to the constraint that you just created. In the "Relation" drop down menu, choose "Less Than or Equal".

This will cause the UILabel to dynamically change it's width depending on the width of the text drawn inside it. When you set the backgroundColor property, it will still fill the label by will only show behind the text. The Equal Widths constraint will make sure that the width of the label never exceeds the width of the image view.

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