Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch width of UILabel according to width of containing text with background image

I have the following problem - I need to create two UI labels along side one another as in the screen shot below -

enter image description here

The UI label containing the special offers text is dynamic and needs to adjust to the width of the containing text and also if possible display the slanted orange background with the relevant padding -

I'm predominantly a Front-end dev - so with CSS i'd use a long background image that aligns to the right of the label and pad accordingly - but I have no idea how to approach this in objective C - can anyone offer any advice?

like image 691
Dancer Avatar asked Dec 30 '25 01:12

Dancer


2 Answers

This is not a drop-in solution, but perhaps helps you find it (assuming you don't use Auto Layout):

  • You need a UIImageView for the background and a UILabel for the text
  • Use a tileable/strechable image (probably with cap insets) for the background (see [UIImage resizableImageWithCapInsets:resizingMode:])
  • Set the text on your label
  • Call [label sizeToFit] to resize the label to exactly fit the contained text
  • Resize the image view depending on the label's size (e.g. imageView.frame = CGRectInset(label.frame, -10, -10), which would make your image view 10pt larger than the label on all sides).

With Auto Layout you'd just define the appropriate constraints between the label and the image view and rely on the label's "intrinsic content size" - should be quite easy.

like image 192
Daniel Rinser Avatar answered Jan 01 '26 17:01

Daniel Rinser


You could always shrink the text when it gets to long for the label, go into your view controller, click on the label that you would like to shrink when the text gets too long, then, go down to Autoshrink under Label in the attributes inspector. Change it from fixed font size to minimum font size, then I recommend putting 6 to 8 as the lowest font size. This is going to be the LOWEST font size though, so if XCode can make the label fit while making the font size 9, yet the lowest is 7, it will do it.

Or, you could get the length of the string with

int *stringLength = [myString length]

which counts spaces too, then, change the orange square with

orangeBoxImageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);

so you could do something like this with your code:

if(stringLength == 15{
    orangeBoxImageView.frame = CGRectMake(0, 0, 15, 5);
}
like image 37
Jojodmo Avatar answered Jan 01 '26 17:01

Jojodmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!