Setting parts of a String to Bold in UIView

2019-06-09 21:42发布

问题:

I'm parsing an XML file an get a string as NSMutableString. Now I want to show this string as text in my UIView. So, I created a TextView and set its value to my string. The result was that I have the text with HTML Tags shown up in the TextView.

There is no problem removing the tags from the string, but some of the text needs to appear as bold.

Is there any way to display parts of a string as bold programmatically?

I replaced <br> Elements with \n and it works fine for line-break.

But I still don't know what I can do to display words between strong tags as bold in the UIView.

回答1:

There are two ways. The first is by displaying them in UIWebViews; prior to iOS 4.1 this was effectively the only way. Because you already have HTML codes in the text, it would certainly be easy.

If you're ok with your app running only on iOS 4.1 and up you can use Core Text, which provides very rich formatting.

EDIT

Apple provides some good resources:

About Text, Web, and Editing Support in iOS

Core Text Programming Guide

WWDC 2010 Session Videos -- follow the link to iTunes and grab session 110: Advanced Text Handling for iPhone OS
(Apple Developer login required)



回答2:

You may use UIWebView and load your content from an NSString object.

Anyway if you want to stick to Cocoa, have a look to NSAttributedString.