swift标签

时间:2018-02-14 20:42:21

标签: swift uilabel nsattributedstring

是否可以使用属性字符串设置标签下方的文字 -

  

标记/总计:m / t(蓝色)

     

位置:p(下一行的红色)

m t p 也是可变的。我想要展示

  

位置:P   用不同的颜色。

基本上我不想使用多个变量并使用属性字符串的所有功能。

1 个答案:

答案 0 :(得分:1)

这样做(见解释说明):

// 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)

这会让你:
enter image description here