【发布时间】:2018-02-20 23:19:00
【问题描述】:
我正在使用带有 Xcode 9.2 的 Swift 4。
我有一个UILabel,在他们的.attributedText 属性中我关联了一个NSMutableAttributedString。其实这个NSMutableAttributedString是由两个不同的NSMutableAttributedString拼接而成的,每个人都有不同的属性。
由于使用append() 我将所有NSMutableAttributedString 合并到一个可变字符串中,如何在附加所有内容之前检索我之前设置的属性范围(可能无法完成)?或者,有一种方法可以在UILabel.attributedText 中放置多个NSMutableAttributedString?或者,我可以在不使用UILabel 的情况下获得这种行为吗(例如,可能使用UITextView)?
这是我遇到的问题,因为我需要添加一个隐藏的UISwitch(= 将其恢复为默认黑色)并在旅途中再次显示此NSMutableAttributedString 的foregroundColor,但由于只有一部分这个字符串有一个foregroundColor 属性,我不能简单地将属性应用到整个字符串上。
这是代码:
func attributedTest (_ testString : String)
{
// the first NSMutableAttributedString created
let firstString = NSMutableAttributedString(
string: testString,
attributes: [NSAttributedStringKey.font : UIFont(
name: "Futura",
size: 20.0)!])
// the second NSMutableAttributedString created, they're equal
let secondString = NSMutableAttributedString(
string: testString,
attributes: [NSAttributedStringKey.font : UIFont(
name: "Futura",
size: 20.0)!])
// here I'm adding the attributed on test2
// the NSRange, in this case, is equal to the whole string
secondString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRangeFromString("0, \(testString.count)"))
// here I'm appending the second string to the first one
firstString.append(secondString)
// here I'm setting the testLabel.attributedText
testLabel.attributedText = test
}
我想到了这个NSMutableAttributedString 的普通副本,根本没有属性(UIFont 在属性之外,所以我不担心),存储在某个地方。拥有这两个字符串并在需要时通过UISwitch 随时切换它们是否是一个不错的解决方案(虽然不是最佳解决方案)?
谢谢!
【问题讨论】:
-
你可以从这里获取范围..stackoverflow.com/questions/25207373/…
标签: ios swift uilabel nsattributedstring