【问题标题】:Attributed string in swift label [closed]swift标签中的属性字符串[关闭]
【发布时间】:2018-02-14 20:42:20
【问题描述】:

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

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

position:p(下一行为红色)

其中 mtp 也是可变的。我要展示

位置:p 不同的颜色。

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

【问题讨论】:

  • 是的,谢谢@Rashwan

标签: swift uilabel nsattributedstring


【解决方案1】:

这样做(参见 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)

这将为您提供:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    相关资源
    最近更新 更多