2020 | SWIFT 5.1:
Anda dapat menambahkan 2 NSMutableAttributedString
dengan cara berikut:
let concatenated = NSAttrStr1.append(NSAttrStr2)
Cara lain bekerja dengan NSMutableAttributedString
dan NSAttributedString
keduanya:
[NSAttrStr1, NSAttrStr2].joinWith(separator: "")
Cara lain adalah ....
var full = NSAttrStr1 + NSAttrStr2 + NSAttrStr3
dan:
var full = NSMutableAttributedString(string: "hello ")
// NSAttrStr1 == 1
full += NSAttrStr1 // full == "hello 1"
full += " world" // full == "hello 1 world"
Anda dapat melakukan ini dengan ekstensi berikut:
// 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
}
}