2020 SWIFT 5.1:
Você pode adicionar 2 NSMutableAttributedString
da seguinte maneira:
let concatenated = NSAttrStr1.append(NSAttrStr2)
Outra maneira funciona com NSMutableAttributedString
e com NSAttributedString
ambos:
[NSAttrStr1, NSAttrStr2].joinWith(separator: "")
Outra maneira é ....
var full = NSAttrStr1 + NSAttrStr2 + NSAttrStr3
e:
var full = NSMutableAttributedString(string: "hello ")
// NSAttrStr1 == 1
full += NSAttrStr1 // full == "hello 1"
full += " world" // full == "hello 1 world"
Você pode fazer isso com a seguinte extensão:
// works with NSAttributedString and NSMutableAttributedString!
public extension NSAttributedString {
static func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString {
let leftCopy = NSMutableAttributedString(attributedString: left)
leftCopy.append(right)
return leftCopy
}
static func + (left: NSAttributedString, right: String) -> NSAttributedString {
let leftCopy = NSMutableAttributedString(attributedString: left)
let rightAttr = NSMutableAttributedString(string: right)
leftCopy.append(rightAttr)
return leftCopy
}
static func + (left: String, right: NSAttributedString) -> NSAttributedString {
let leftAttr = NSMutableAttributedString(string: left)
leftAttr.append(right)
return leftAttr
}
}
public extension NSMutableAttributedString {
static func += (left: NSMutableAttributedString, right: String) -> NSMutableAttributedString {
let rightAttr = NSMutableAttributedString(string: right)
left.append(rightAttr)
return left
}
static func += (left: NSMutableAttributedString, right: NSAttributedString) -> NSMutableAttributedString {
left.append(right)
return left
}
}