CodeGeek123
CodeGeek123

Reputation: 4501

Embedding Image and UILable in UIWebView

I am receiving an image, title and description from a json file and i need to display this on a view. I am using webview because the description attribute has links and is in html format so webview is easiest. However now i need to add the image and title above the description. I know how i can add an image seperately but i dont know how i can add all these three components in the webview. Any help? Thank you

NSString * myHTMLImage = @"<img src='Hop.png'>";
NSString *imagePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:imagePath];
[self.webView loadHTMLString:myHTMLImage baseURL:baseURL];

The above code embeds an image to the entire webview.

[self.webView loadHTMLString:bodyOfText baseURL:nil]; 

I need to be able to do the above loading of bodyOfText as wel. and a title too. which is a string. How do i do it.

Upvotes: 0

Views: 344

Answers (2)

Rob
Rob

Reputation: 437632

You just build up your HTML string. You could do something like:

NSString *title      = @"this is my title";
NSString *body       = [NSString stringWithFormat:@"Blah, blah, blah<p>%@<p>", self.bodyOfText.text];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *imgPath    = [bundlePath stringByAppendingPathComponent:@"Hop.png"];
NSURL    *imgUrl     = [NSURL fileURLWithPath:imgPath];

NSString *html = [NSString stringWithFormat:
                  @"<html>"
                  "<header>"
                  "<title>%@</title>"
                  "</header>"
                  "<body>"
                  "%@"
                  "<img src=\"%@\">"
                  "</body>"
                  "</html>",
                  title, body, [imgUrl absoluteString]];

[self.webView loadHTMLString:html baseURL:nil];

I usually build my references to images right in the src tag, that way I can easily refer to both images in my bundle as well as images in my Documents folder in the same HTML string.

Upvotes: 1

Michael Mangold
Michael Mangold

Reputation: 1801

You could add these programmatically as UILabel subviews, or through the storyboard by dragging out a label and hooking them up as IBOutlets.

Upvotes: 1

Related Questions