gpt4 book ai didi

ios - 如何使用 Swift 在 iOS 中使用 NSAttributedStrings?

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:30 25 4
gpt4 key购买 nike

我想要一个带有在运行时动态变化的属性字符串的标签。像这样

enter image description here

有没有更好的方法来动态更改价格值,而无需对属性键字典进行硬编码并手动构建 NSAttributedString

最佳答案

在 iOS 上处理属性字符串的最佳方法是使用界面构建器中的内置属性文本编辑器,并避免在源文件中对 NSAtributedStringKeys 进行不必要的硬编码。

您稍后可以使用此扩展在运行时动态替换 placehoderls:

extension NSAttributedString {
func replacing(placeholder:String, with valueString:String) -> NSAttributedString {

if let range = self.string.range(of:placeholder) {
let nsRange = NSRange(range,in:valueString)
let mutableText = NSMutableAttributedString(attributedString: self)
mutableText.replaceCharacters(in: nsRange, with: valueString)
return mutableText as NSAttributedString
}
return self
}
}

添加一个带有属性文本的 Storyboard标签,如下所示。

enter image description here

然后您只需在每次需要时更新值,如下所示:

label.attributedText = initalAttributedString.replacing(placeholder: "<price>", with: newValue)

确保将原始值保存到 initalAttributedString 中。

您可以通过阅读这篇文章更好地理解这种方法: https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e

关于ios - 如何使用 Swift 在 iOS 中使用 NSAttributedStrings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094958/

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