-2

I have Two NSAttributed String but when I concate like

self.label.text = attrStr1 + attrStr2 //gives error

     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)!

Also can we concate one NSAttributedString and another NSString?

New iOS Dev
  • 1,937
  • 7
  • 33
  • 67

2 Answers2

6
     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)!

Concatenate this strings :

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

self.label.text = concate
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
1

2020 | SWIFT 5.1: You're able to add 2 NSAttributedString this like:

let concatenated =  NSAttrStr1.append(NSAttrStr2)

Also there is exist another better answer on the same question here: https://stackoverflow.com/a/60329354/4423545

Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101