如何在 Swift 中连接两个 NSAttributedString?

问题描述 投票:0回答:2

我有两个 NSAttributedString:

var attrStr1: NSAttributedString = NSAttributedString(data: "
<b>Welcome</b>".dataUsingEncoding(NSUnicodeStringEncoding, 
allowLossyConversion: true)!,options: [ NSDocumentTypeDocumentAttribute:
 NSHTMLTextDocumentType],documentAttributes: nil,error: nil)!

var attrStr2: NSAttributedString = NSAttributedString(data: "
<i>User</i>".dataUsingEncoding(NSUnicodeStringEncoding, 
allowLossyConversion: true)!,options: [ NSDocumentTypeDocumentAttribute: 
NSHTMLTextDocumentType],documentAttributes: nil,error: nil)!

当我像这样连接它们时:

self.label.text = attrStr1 + attrStr2

我收到错误。

如何连接两个 NSAttributedString?

是否可以连接 NSAttributedString 和 NSString?

ios iphone swift
2个回答
7
投票
     var attrStr1: NSAttributedString = NSAttributedString(data: "
<b>Welcome</b>".dataUsingEncoding(NSUnicodeStringEncoding, 
allowLossyConversion: true)!,options: [ NSDocumentTypeDocumentAttribute:
 NSHTMLTextDocumentType],documentAttributes: nil,error: nil)!

    var attrStr2: NSAttributedString = NSAttributedString(data: "
<i>User</i>".dataUsingEncoding(NSUnicodeStringEncoding, 
allowLossyConversion: true)!,options: [ NSDocumentTypeDocumentAttribute: 
NSHTMLTextDocumentType],documentAttributes: nil,error: nil)!

连接此字符串:

var concate = NSMutableAttributedString(attributedString: attrStr1)
concate.appendAttributedString(attrStr2)

self.label.text = concate

2
投票

2020 |环球银行金融电信协会 5.1: 您可以添加 2 个 NSAttributedString,如下所示:

let concatenated =  NSAttrStr1.append(NSAttrStr2)

同样的问题还有另一个更好的答案: https://stackoverflow.com/a/60329354/4423545

© www.soinside.com 2019 - 2024. All rights reserved.