gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:18:20 24 4
gpt4 key购买 nike

如何只设置一次 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

最佳答案

您可以声明一个 mutableAttributed string 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
}

}

关于ios - UILabel.attributedText 设置属性一次,然后只更改文本(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48702078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com