3

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!

Daniel
  • 521
  • 1
  • 7
  • 16

1 Answers1

4

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)
Majster
  • 3,611
  • 5
  • 38
  • 60
  • Thank you so much!! but it doesn't have any attributes! how can I fix this? – Daniel Sep 27 '16 at 11:01
  • You can add attributes as you see fit. For example you can use `str.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(0, 8))` (this is swift3, for swift2.x use `UIColor.redColor()`) to make the word `Hardcore` red. It won't show in `print()` tough. You must use a `UILabel` in order to see what it will look like. – Majster Sep 27 '16 at 11:03
  • Thanks... but my problem is replace the attributed text **keeping** it's own attributes. (I used UILabel...) – Daniel Sep 27 '16 at 11:11
  • How do you convert your string into the `NSMutableAttributedString`? Did you try using `NSMutableAttributedString(attributedString: yourStr)`? – Majster Sep 27 '16 at 11:18
  • I'm very sorry... that was my fault. It doesn't worked because I add **let** to replaceOccurrence. It works fine now!! Thank for helping!! – Daniel Sep 27 '16 at 11:20