Search code examples
iosswiftuitableviewnsattributedstringnsregularexpression

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


I'm making a Note-Taking-App. I save Attributed text On DetailVC and I show the preview in the UITableViewCell label.

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

 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?

pls help!


Solution

  • You can make a NSMutableAttributedString which is an attributed string which allows mutation of its contents and then use the property mutableString of it.

    If you already have a NSAttributedString you can use mutableCopy() or take a look at 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)