在NSString或nsmutablestring中不可能有多种颜色。我听说过一点NSAttributedString,它是在iPad SDK 3.2(或大约3.2)中引入的,并且在iPhone SDK 4.0 beta版中可用。
我想要一根有三种颜色的绳子。
我不使用3个独立的NSString的原因,是因为三个NSAttributedString子字符串的长度经常改变,所以我宁愿,不使用任何计算重新定位3个独立的NSString对象。
如果使用NSAttributedString是可能的,我怎么做以下-(如果不可能使用NSAttributedString,你会怎么做):
编辑:
记住,@"first", @"second"和@"third"随时会被其他字符串替换。所以使用硬编码的NSRange值是行不通的。
我做了一个库,使这更容易。看看ZenCopy吧。
您可以创建Style对象,和/或将它们设置为稍后引用的键。是这样的:
ZenCopy.manager.config.setStyles {
return [
"token": Style(
color: .blueColor(), // optional
// fontName: "Helvetica", // optional
fontSize: 14 // optional
)
]
}
然后,你可以很容易地构造字符串和样式,并有参数:)
label.attributedText = attributedString(
["$0 ".style("token") "is dancing with ", "$1".style("token")],
args: ["JP", "Brock"]
)
你也可以很容易地用正则表达式搜索样式!
let atUserRegex = "(@[A-Za-z0-9_]*)"
mutableAttributedString.regexFind(atUserRegex, addStyle: "token")
这将使用'token'样式对前面带有'@'的所有单词进行样式化。(例如@jpmcglone)
我需要仍然得到它工作w/一切NSAttributedString所提供的,但我认为fontName, fontSize和颜色涵盖了它的大部分。期待很快会有很多更新:)
如果你需要,我可以帮你开始。同时也在寻求反馈,所以如果它能让你的生活更轻松,我就说任务完成了。
斯威夫特4
let combination = NSMutableAttributedString()
var part1 = NSMutableAttributedString()
var part2 = NSMutableAttributedString()
var part3 = NSMutableAttributedString()
let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]
let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]
let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
NSAttributedStringKey.foregroundColor: UIColor.red]
if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{
part1 = NSMutableAttributedString(string: "first", attributes: regular)
}
if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{
part2 = NSMutableAttributedString(string: "second", attributes: bold)
}
if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{
part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)
}
combination.append(part1)
combination.append(part2)
combination.append(part3)
属性列表请参见这里的NSAttributedStringKey在苹果文档
我做了一个库,使这更容易。看看ZenCopy吧。
您可以创建Style对象,和/或将它们设置为稍后引用的键。是这样的:
ZenCopy.manager.config.setStyles {
return [
"token": Style(
color: .blueColor(), // optional
// fontName: "Helvetica", // optional
fontSize: 14 // optional
)
]
}
然后,你可以很容易地构造字符串和样式,并有参数:)
label.attributedText = attributedString(
["$0 ".style("token") "is dancing with ", "$1".style("token")],
args: ["JP", "Brock"]
)
你也可以很容易地用正则表达式搜索样式!
let atUserRegex = "(@[A-Za-z0-9_]*)"
mutableAttributedString.regexFind(atUserRegex, addStyle: "token")
这将使用'token'样式对前面带有'@'的所有单词进行样式化。(例如@jpmcglone)
我需要仍然得到它工作w/一切NSAttributedString所提供的,但我认为fontName, fontSize和颜色涵盖了它的大部分。期待很快会有很多更新:)
如果你需要,我可以帮你开始。同时也在寻求反馈,所以如果它能让你的生活更轻松,我就说任务完成了。