Ios 如何在swift中连接两个NSA指定的字符串?
我有两个NSA指定的字符串,但当我 self.label.text=attrStr1+attrStr2//出现错误Ios 如何在swift中连接两个NSA指定的字符串?,ios,iphone,swift,Ios,Iphone,Swift,我有两个NSA指定的字符串,但当我 self.label.text=attrStr1+attrStr2//出现错误 var attrStr1: NSAttributedString = NSAttributedString(data: " <b>Welcome</b>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,options: [ NSDocumentTyp
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 attrStr1:nsattributestring=nsattributestring(数据:
欢迎使用“.dataUsingEncoding(NSU编码),
allowLossyConversion:true)!,选项:[NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType],文档属性:无,错误:无)!
var属性R2:NSAttributedString=NSAttributedString(数据:
用户“.dataUsingEncoding(NSU编码),
allowLossyConversion:true)!,选项:[NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType],文档属性:无,错误:无)!
我们还可以将一个NSAttribute字符串与另一个NSString关联起来吗?2020 | SWIFT 5.1:
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)!
您可以添加2个NSAttributed字符串,如下所示:
let concatenated = NSAttrStr1.append(NSAttrStr2)
对于同一个问题,这里还有另一个更好的答案:
阅读文档。您需要NSMutableAttributedString,它有一个appendAttributedString方法。不读取文档只是懒散的AttrStr1。appendAttributedString(attrStr2)已尝试但没有成功,因为NSAttributeString不是NSMutableAttributedString。出现错误“void不能转换为”NSAttributedString“即使我使用NSMutableAttributedStrings,这也是因为该方法不返回任何内容,而您正试图使用它设置字符串。此方法将改变正在调用它的字符串。显示您使用的代码。二进制运算符“+”不能应用于两个“NSAttributedString”操作数,错误为:无法将“Void”类型的值转换为指定类型“NSMutableAttributedString”。我找不到这些错误的原因。@shtefane这意味着您的NSAttrStr2无效,但不是NSMutableAttributedString
let concatenated = NSAttrStr1.append(NSAttrStr2)