gpt4 book ai didi

swift - NSMutableAttributedString 的可变大小范围

转载 作者:行者123 更新时间:2023-11-30 11:28:18 27 4
gpt4 key购买 nike

我有一个带有如下所示字符串的标签。我希望 SecondVariable 具有不同的颜色。我想我明白如何改变颜色。我的问题是获取 secondVariable 的范围。

let str = "\(firstVariable) some random text \(secondVariable)"

let secondVariableRange = str.range(???)
let secondVariableNSRange = NSRange(secondVariableRange, in: str)

let attributedString = NSMutableAttributedString.init(string:
"\(firstVariable) some random text \(secondVariable)")

attributedString.addAttribute(.foregroundColor, value: UIColor.white,
range: NSRange(secondVariableNSRange, in: attributedString)

最佳答案

有一种比处理范围更简单的方法。分段构建您的属性字符串。

let attributedString = NSMutableAttributedString(string: 
"\(firstVariable) some random text ")
let attrs: [NSAttributedStringKey : Any] = [ .foregroundColor: UIColor.white ]
let secondString = NSAttributedString(string: "\(secondVariable)", attributes: attrs)
attributedString.append(secondString)

但是如果您确实想获得范围,请使用:

let secondVariableRange = (str as NSString).range(of: "\(secondVariable)")

关于swift - NSMutableAttributedString 的可变大小范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513459/

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