-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,711
  • 6
  • 29
  • 50

2 Answers2

4
     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,020
  • 11
  • 96
  • 132
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