gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:00:47 25 4
gpt4 key购买 nike

下面的代码为整个 UILabel 创建了一个背景。

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

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

最佳答案

这是一个使用属性字符串的例子:

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)

关于ios - 根据 UILabel 的宽度设置背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32075059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com