根据UILabel的宽度设置背景颜色

时间:2015-08-18 14:20:15

标签: ios swift uilabel

以下代码为整个UILabel创建了背景。

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

现在,我需要根据UILabel的文本长度来限制它的宽度。应该仅为文本的长度绘制背景颜色,该长度可以是不同的长度,而不是视图占据的整个空间。它应该类似于聊天应用程序,背景应根据文本宽度进行调整。

1 个答案:

答案 0 :(得分:0)

以下是使用属性字符串的示例:

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)