ios - swift - 如何删除 NSAttributedString 中的空白(空)行?

标签 ios swift uitableview nsattributedstring nsregularexpression

我正在制作一个笔记应用程序。 我将 Attributed text 保存在 DetailVC 上 并在 UITableViewCell 标签 中显示预览。

在标签中我有这样的文字

The Bold Title

my Text

我想这样改

The Bold Title
my Text

我在 String 中找到了解决方案

 let regex = try! NSRegularExpression(pattern: "\n+", options: [])
 let newString = regex.stringByReplacingMatches(in: MyString, options: [], range: NSRange(location: 0, length: MyString.characters.count), withTemplate: "\n")

但是我如何在 NSAttirbutedString 中做到这一点?

请帮忙!

最佳答案

你可以创建一个NSMutableAttributedString,它是一个允许改变其内容的属性字符串,然后使用它的属性mutableString

如果您已经有了 NSAttributedString,您可以使用 mutableCopy() 或查看 possible initializers of NSMutableAttributedString .

let str = NSMutableAttributedString(string: "Hardcore\n\nHenry")
str.mutableString.replaceOccurrences(of: "\n\n", with: "\n", options: [], range: NSMakeRange(0, str.length))
print(str)

关于ios - swift - 如何删除 NSAttributedString 中的空白(空)行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39722509/

相关文章:

ios - 完全移动到其他 View 并且不允许在 SwiftUI 中返回

ios - 旋转时的 UICollectionViewCell alpha 值

ios - UITableViewCell : get the exact width of UILabel in cell

ios - 检查表格 View 单元格上的签名

ios - Facebook 登录 iOS 错误 : The operation couldn’t be completed.(com.facebook.sdk.core 错误 3。)

ios - NSMutableArray 内的 NSMutableArray Swift

ios - 如何修复文本标签阴影布局

json - 如何使用不同的键从 JSON 中获取数据?

swift - 调整 UITextView 和包含它的部分的大小,而不过度绘制下一个 tableview 部分

ios - 仅在 TableView 的特定单元格上显示和隐藏 View