首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何连接NSAttributedStrings?

如何连接NSAttributedStrings?
EN

Stack Overflow用户
提问于 2013-08-30 02:15:18
回答 7查看 99.9K关注 0票数 168

在合并字符串之前,我需要搜索一些字符串并设置一些属性,所以让NSStrings ->连接它们-> Make NSAttributedString是不可行的,有没有办法将attributedString连接到另一个attributedString?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2013-08-30 02:22:48

我建议您使用a @Linuxios建议的单个可变属性字符串,下面是另一个示例:

代码语言:javascript
复制
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:将事实后的属性添加到包含输入字符串的范围中。不过,我推荐使用前一种方法。

票数 217
EN

Stack Overflow用户

发布于 2015-09-19 23:37:33

如果你使用的是Swift,你只需要重载+操作符,这样你就可以像连接普通字符串一样连接它们:

代码语言:javascript
复制
// concatenate attributed strings
func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString
{
    let result = NSMutableAttributedString()
    result.append(left)
    result.append(right)
    return result
}

现在,只需将它们相加即可将它们连接起来:

代码语言:javascript
复制
let helloworld = NSAttributedString(string: "Hello ") + NSAttributedString(string: "World")
票数 98
EN

Stack Overflow用户

发布于 2017-06-15 01:53:40

Swift 3:只需创建一个NSMutableAttributedString并将属性字符串附加到它们。

代码语言:javascript
复制
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更新:

代码语言:javascript
复制
    let captionAttribute = [
        NSAttributedString.Key.font: Font.captionsRegular,
        NSAttributedString.Key.foregroundColor: UIColor.appGray
    ]
票数 39
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18518222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档