use*_*r25 4 nsattributedstring uilabel ios swift
如何仅设置 UILabel 文本属性一次,然后仅更改文本(字符串)
mTextValue.attributedText = NSAttributedString(string: "STRING",
attributes:
[NSAttributedStringKey.strokeWidth: -3.0,
NSAttributedStringKey.strokeColor: UIColor.black])
mTextValue.text = "NEW STRING" // won't change anything
Run Code Online (Sandbox Code Playgroud)
或者要设置新字符串,我必须一次又一次地NSAttributedString设置吗?.attributedText
您可以声明一个 mutableAttributed 字符串分隔符并更改它的字符串,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
完整示例:
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
}
}
Run Code Online (Sandbox Code Playgroud)