2

The below code creates a background for an entire UILabel.

view.layer.masksToBounds = true
view.layer.cornerRadius = 8.0
view.layer.backgroundColor = UIColor.greenColor().CGColor
view.layer.borderWidth = 3.0

Now, I need to restrict it's width based on the text length of UILabel. The background color should only be drawn for the length of the text which can be of different length, not the entire space taken up by view. It should be similar to chat app, the background should adjust based on the text width.

Nigilan
  • 766
  • 1
  • 6
  • 20
  • Checkout [NSMutableAttributedString](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/) and this question/answer: [Highlight just the text in a UILabel](http://stackoverflow.com/q/31293873/2108547) – Daniel Storm Aug 18 '15 at 14:22
  • Have you tried to do the same on UILabel with sizeToFit() afterwards? – Miknash Aug 18 '15 at 14:24
  • I think I need to edit the question! I need to give the background dynamically to the UILabel based on the text length. Similar to chat app, it should adjust the length of the UILabel backgroud. – Nigilan Aug 18 '15 at 19:15

1 Answers1

0

Here's an example using an attributed string:

var myString1 = NSMutableAttributedString(string:"this is probably what you want")

let myString1Font1 = UIFont(name:"Helvetica", size:14.0)

let myString1Color1 = UIColor(red: 1.000000, green: 0.976471, blue: 0.349020, alpha: 1.000000)
let myString1Color2 = UIColor(red: 0.850980, green: 0.043137, blue: 0.000000, alpha: 1.000000)

let originalNSString = myString1.string as NSString
let myString1Range1 = originalNSString.rangeOfString("this is probably what you want")

var myString1ParaStyle1 = NSMutableParagraphStyle()
myString1ParaStyle1.alignment = NSTextAlignment.Natural
myString1ParaStyle1.baseWritingDirection = NSWritingDirection.Natural
myString1ParaStyle1.lineBreakMode = NSLineBreakMode.ByWordWrapping


myString1.addAttribute(NSParagraphStyleAttributeName, value:myString1ParaStyle1, range:myString1Range1)
myString1.addAttribute(NSBackgroundColorAttributeName, value:myString1Color1, range:myString1Range1)
myString1.addAttribute(NSFontAttributeName, value:myString1Font1!, range:myString1Range1)
myString1.addAttribute(NSForegroundColorAttributeName, value:myString1Color2, range:myString1Range1)
Larry Pickles
  • 4,615
  • 2
  • 19
  • 36