UILabel.attributedText设置属性一次,然后只更改文本(字符串)

时间:2018-02-09 08:59:00

标签: ios swift uilabel nsattributedstring

如何只设置一次UILabel文本属性,然后只更改文本(字符串)

mTextValue.attributedText = NSAttributedString(string: "STRING", 
       attributes: 
           [NSAttributedStringKey.strokeWidth: -3.0,      
            NSAttributedStringKey.strokeColor: UIColor.black])


mTextValue.text = "NEW STRING" // won't change anything

或设置新字符串我是否必须一次又一次地将NSAttributedString设置为.attributedText

1 个答案:

答案 0 :(得分:4)

你可以声明一个mutableAttributed字符串separat并改变它的字符串,如下所示:

let yourString = "my string"
let yourAttributes = [NSAttributedStringKey.strokeWidth: -3.0, NSAttributedStringKey.strokeColor: UIColor.black] as [NSAttributedStringKey : Any]
let mutableAttributedString = NSMutableAttributedString(string: yourString, attributes: yourAttributes)

let yourNewString = "my new string"
mutableAttributedString.mutableString.setString(yourNewString)

完整示例:

import UIKit

class ViewController: UIViewController {

    var mutableAttributedString = NSMutableAttributedString()

    @IBAction func buttonTapped(_ sender: Any) {

        mutableAttributedString.mutableString.setString("new string")
        mainLabel.attributedText = mutableAttributedString

    }

    @IBOutlet weak var mainLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let yourString = "my string"
        let yourAttributes = [NSAttributedStringKey.strokeWidth: -3.0, NSAttributedStringKey.strokeColor: UIColor.blue] as [NSAttributedStringKey : Any]
        mutableAttributedString = NSMutableAttributedString(string: yourString, attributes: yourAttributes)

        mainLabel.attributedText = mutableAttributedString
    }

}