gpt4 book ai didi

ios - Swift NSAttributedString 修剪

转载 作者:IT王子 更新时间:2023-10-29 05:18:54 24 4
gpt4 key购买 nike

我想去掉 NSAttributedString(Trimming it) 前面和结尾的空白。我不能简单地将它转换为字符串并进行修剪,因为其中有图像(附件)。我该怎么做?

最佳答案

如下所示创建 NSAttributedString 的扩展。

extension NSAttributedString {
public func attributedStringByTrimmingCharacterSet(charSet: CharacterSet) -> NSAttributedString {
let modifiedString = NSMutableAttributedString(attributedString: self)
modifiedString.trimCharactersInSet(charSet: charSet)
return NSAttributedString(attributedString: modifiedString)
}
}

extension NSMutableAttributedString {
public func trimCharactersInSet(charSet: CharacterSet) {
var range = (string as NSString).rangeOfCharacter(from: charSet as CharacterSet)

// Trim leading characters from character set.
while range.length != 0 && range.location == 0 {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: charSet)
}

// Trim trailing characters from character set.
range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
while range.length != 0 && NSMaxRange(range) == length {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
}
}
}

并在您要使用的 viewController 中使用。像这样

let attstring = NSAttributedString(string: "this is test message. Please wait.                   ")
let result = attstring.attributedStringByTrimmingCharacterSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

关于ios - Swift NSAttributedString 修剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38737920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com