Adding formatted text to iOS applications – UIWebView, HTML from a string.

You would think that this would be easy as can be? Surly there must be a text box with formatting built in?? Apparently that is not the case. You can obviously use core graphics and render some text any way you like, but that just didn’t fit into what I was doing. The best method I could find was to just use UIWebView.

This is really rather simple. Below are the steps you need to take to use this with text:

  1. In UI builder add a UIWebView object to your view
  2. Add an Outlet to your header file:
    @property (nonatomic, retain) IBOutlet UIWebView *formattedTextView;
  3. Add a property or variable to store the HTMl:
    @property (nonatomic, copy) NSString *theHTML;
  4. Synthesize the properties and of course release them in the dealloc method:
    @synthesize theHTML = _theHTML;
    @synthesize formattedTextView = _formattedTextView;
    
    [_theHTML release];
    [_FormattedTextView release];
  5. In the implementation of the view add the html and assign it to the control, in my case I did this in didFinishLaunchingWithOptions you simply use loadHTMLString with a nil base URL:
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    self.theHTML = @"<html> \
    <head> \
    </head> \
    <body> \
    <p>Hello World<p> \
    </body>
    </html>";
    [self.formattedTextView loadHTMLString:self.theHTML baseURL:nil];
    // Override point for customization after application launch.
    [self.window makeKeyAndVisible];
    return YES;
    }

 

Not a hell of a lot to it really.

Would love to hear from anyone who knows of a better way to do this 😉

 

2 Replies to “Adding formatted text to iOS applications – UIWebView, HTML from a string.”

  1. Hi,

    thanks for the great tutorial above.
    I am wondering how to use 2 UIWebView on 2 different screens.

    I followed your instructions above and got it working for one screen, but then when i go to the next screen and added a new UIWebView, i am not sure what to do next.

    Please can get help from you on this?

    Thanks,
    Daniel

    1. Sorry I haven’t looked at my blog in a while. Busy time of year. You repeat the same process for your second screen. You can always email me on shanejh at ihug dot co dot nz and I may be able to help.

Comments are closed.