简体   繁体   English

swift - 如何在NSAttributedString中删除空行(空)?

[英]swift - how can I remove blank(empty) line in NSAttributedString?

I'm making a Note-Taking-App. 我正在制作一个Note-Taking-App。 I save Attributed text On DetailVC and I show the preview in the UITableViewCell label . 我保存归因文本在DetailVC上,我在UITableViewCell标签中显示预览。

In the label I have a text like this 在标签中我有这样的文字

The Bold Title

my Text

and I want to change this like 而我想改变它

The Bold Title
my Text

I found the solution in String 我在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")

but how can I do it in NSAttirbutedString ? 但我怎么能在NSAttirbutedString中做到这一点

pls help! 请帮忙!

You can make a NSMutableAttributedString which is an attributed string which allows mutation of its contents and then use the property mutableString of it. 你可以创建一个NSMutableAttributedString ,它是一个允许变换其内容的属性字符串,然后使用它的属性mutableString

If you already have a NSAttributedString you can use mutableCopy() or take a look at possible initializers of NSMutableAttributedString . 如果您已经有NSAttributedString ,则可以使用mutableCopy()或查看NSMutableAttributedString的可能初始值设定项

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM