swift 标签中的属性字符串
Attributed string in swift label
是否可以使用属性字符串在标签下方设置文本-
marks/total:m/t (Blue Color)
position:p (red Color on next line)
其中m、t和p也是可变的。我要展示
position:p
in different color.
基本上我不想使用多个变量并使用属性字符串的所有功能。
这样做(解释见评论):
// 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)
这会让你:
是否可以使用属性字符串在标签下方设置文本-
marks/total:m/t (Blue Color)
position:p (red Color on next line)
其中m、t和p也是可变的。我要展示
position:p in different color.
基本上我不想使用多个变量并使用属性字符串的所有功能。
这样做(解释见评论):
// 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)
这会让你: