在合并字符串之前,我需要搜索一些字符串并设置一些属性,所以让NSStrings ->连接它们-> Make NSAttributedString是不可行的,有没有办法将attributedString连接到另一个attributedString?
发布于 2013-08-30 02:22:48
我建议您使用a @Linuxios建议的单个可变属性字符串,下面是另一个示例:
NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init];
NSString *plainString = // ...
NSDictionary *attributes = // ... a dictionary with your attributes.
NSAttributedString *newAttString = [[NSAttributedString alloc] initWithString:plainString attributes:attributes];
[mutableAttString appendAttributedString:newAttString];
但是,为了获得所有选项,您还可以创建一个可变的属性字符串,该字符串由包含已经放在一起的输入字符串的格式化NSString组成。然后,可以使用addAttributes: range:
将事实后的属性添加到包含输入字符串的范围中。不过,我推荐使用前一种方法。
发布于 2015-09-19 23:37:33
如果你使用的是Swift,你只需要重载+
操作符,这样你就可以像连接普通字符串一样连接它们:
// concatenate attributed strings
func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString
{
let result = NSMutableAttributedString()
result.append(left)
result.append(right)
return result
}
现在,只需将它们相加即可将它们连接起来:
let helloworld = NSAttributedString(string: "Hello ") + NSAttributedString(string: "World")
发布于 2017-06-15 01:53:40
Swift 3:只需创建一个NSMutableAttributedString并将属性字符串附加到它们。
let mutableAttributedString = NSMutableAttributedString()
let boldAttribute = [
NSFontAttributeName: UIFont(name: "GothamPro-Medium", size: 13)!,
NSForegroundColorAttributeName: Constants.defaultBlackColor
]
let regularAttribute = [
NSFontAttributeName: UIFont(name: "Gotham Pro", size: 13)!,
NSForegroundColorAttributeName: Constants.defaultBlackColor
]
let boldAttributedString = NSAttributedString(string: "Warning: ", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "All tasks within this project will be deleted. If you're sure you want to delete all tasks and this project, type DELETE to confirm.", attributes: regularAttribute)
mutableAttributedString.append(boldAttributedString)
mutableAttributedString.append(regularAttributedString)
descriptionTextView.attributedText = mutableAttributedString
swift5更新:
let captionAttribute = [
NSAttributedString.Key.font: Font.captionsRegular,
NSAttributedString.Key.foregroundColor: UIColor.appGray
]
https://stackoverflow.com/questions/18518222
复制相似问题