Search code examples
iosiphoneswift

How to concatenate two NSAttributedStrings in Swift?


I have two NSAttributedStrings:

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

When I concatenate them like this:

self.label.text = attrStr1 + attrStr2

I get an error.

How can I concatenate two NSAttributedStrings?

Is it possible to concatenate an NSAttributedString and an NSString?


Solution

  •      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