【发布时间】:2018-02-14 20:42:20
【问题描述】:
是否可以使用属性字符串来设置标签上的文本下方-
标记/总计:m/t(蓝色)
position:p(下一行为红色)
其中 m、t 和 p 也是可变的。我要展示
位置:p 不同的颜色。
基本上我不想使用多个变量并使用属性字符串的所有功能。
【问题讨论】:
-
是的,谢谢@Rashwan
标签: swift uilabel nsattributedstring
是否可以使用属性字符串来设置标签上的文本下方-
标记/总计:m/t(蓝色)
position:p(下一行为红色)
其中 m、t 和 p 也是可变的。我要展示
位置:p 不同的颜色。
基本上我不想使用多个变量并使用属性字符串的所有功能。
【问题讨论】:
标签: swift uilabel nsattributedstring
这样做(参见 cmets 的解释):
// create your variables, the length does not matter since this is a dynamic solution
let p = "1234"
let m = "30"
let t = "23"
// Create the string
let str = "marks/total:\(m)/\(t)\nposition:\(p)"
// Create the NSMutableAttributedString
let attrStr = NSMutableAttributedString(string: str)
// Find the range of position in your string
if let range = str.range(of: "position") {
// get start and end position for your word "position"
let start = str.distance(from: str.startIndex, to: range.lowerBound)
let end = str.distance(from: str.startIndex, to: range.upperBound)
// Color position
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSRange(location: start, length: end - start))
}
let label = UILabel(frame: CGRect(x: 100, y: 100, width: 300, height: 100))
label.numberOfLines = 0
label.attributedText = attrStr
self.view.addSubview(label)
【讨论】: