swift - 如何删除 NSAttributedString 中的空白(空)行?
swift - how can I remove blank(empty) line in NSAttributedString?
我正在制作一个笔记应用程序。
我在 DetailVC 上保存 Attributed text
我在 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)
我正在制作一个笔记应用程序。 我在 DetailVC 上保存 Attributed text 我在 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)