0

I am currently writing my first app on ios using swift 3. I have a plist that has a list of different pieces of information and each is a long paragraph with sections throughout it. for each section, I want to bold the text for the title or at least have the option to format it a certain way rather than just display all the text. I currently have a simple table view that displays text in a text view once tapped. I cannot figure out how to read the paragraph into a string, and compare parts of the string and bold that specific text.

For example, If I had a string that was read from the plist and said:

"My name is @Bob and I like to @dance."

How could I change "@Bob" to "Bob" and "@dance" to "dance" without hard coding it?

@IBOutlet var paragraphTextView: UITextView!
.
.
.

if let text = paragraph["Text"] {
        paragraphTextView.text = text
}
  • Sorry but you can do this only with `AttributedString` https://developer.apple.com/reference/uikit/uitextfield#1968630 – Adrian Bobrowski May 07 '17 at 16:57
  • This might be a starting point: http://stackoverflow.com/questions/43557044/bold-words-that-start-with-letter/43557605#43557605 – vadian May 07 '17 at 17:12

1 Answers1

0

The simplest solution is to use some HTML markup in the text in your plist file.

Instead of the plain text:

My name is @Bob and I like to @dance.

Use:

My name is <b>Bob</b> and I like to <b>dance</b>.

This gives you far more flexibility. You can add bold, underline, and italic simply by using the appropriate <b></b>, <u></u>, and <i></i> tags as needed. It also allows you to markup more general ranges than single words.

Once the text has the proper markup, you create an NSAttributedString from the marked up string and then set that to the text viewsattributedTextproperty instead of using thetext` property.

For a good example of how to create an NSAttributedString from HTML text, see HTML Format in UITextView

Community
  • 1
  • 1
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thank you for the quick response. I will try this, but I have no doubt it will work. I was looking for something like this but I guess was unsure if it was possible. – Aaron Welborn May 07 '17 at 18:05
  • EDIT: It worked exactly as planned. Thank you very much! – Aaron Welborn May 07 '17 at 18:35
  • How did you get the to work inside a plist which is already XML?? I get this error message; error: unable to read input file as a property list: The operation couldn’t be completed. (XCBUtil.PropertyListConversionError error 1.) – user3561494 Jul 01 '19 at 15:33
  • @user3561494 You escape the `<` as `<` just like any normal XML. – rmaddy Jul 01 '19 at 16:10