快速回答但是如果你将它翻译成Obj-C(或者只是使用你的Obj-C中使用的扩展名制作一个swift文件)它会给你一个开始
extension NSMutableAttributedString { func trimmedAttributedString(set: CharacterSet) -> NSMutableAttributedString { let invertedSet = set.inverted var range = (string as NSString).rangeOfCharacter(from: invertedSet) let loc = range.length > 0 ? range.location : 0 range = (string as NSString).rangeOfCharacter( from: invertedSet, options: .backwards) let len = (range.length > 0 ? NSMaxRange(range) : string.characters.count) - loc let r = self.attributedSubstring(from: NSMakeRange(loc, len)) return NSMutableAttributedString(attributedString: r) } }
用法:
let noSpaceAttributedString = attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines)
Swift 4及以上
我们可以创建扩展在NSMutableAttributedString
其返回新NSAttributedString
通过去除.whitespacesAndNewlines
extension NSMutableAttributedString { func trimmedAttributedString() -> NSAttributedString { let invertedSet = CharacterSet.whitespacesAndNewlines.inverted let startRange = string.rangeOfCharacter(from: invertedSet) let endRange = string.rangeOfCharacter(from: invertedSet, options: .backwards) guard let startLocation = startRange?.upperBound, let endLocation = endRange?.lowerBound else { return NSAttributedString(string: string) } let location = string.distance(from: string.startIndex, to: startLocation) - 1 let length = string.distance(from: startLocation, to: endLocation) + 2 let range = NSRange(location: location, length: length) return attributedSubstring(from: range) } }