In tutorials by 5 Comments

How to add Dynamic height UIWebView to UITableView

Adding Dynamic Height UIWebView to UITableView using Objective-C

In iOS applications, displaying multimedia and rich contents seems to be an important and integral aspect of social networking applications like Twitter, Facebook.

That too displaying the dynamic contents are often seen as a challenge, but with the help of UIWebView these challenges can be addressed.

This tutorial addresses the above mentioned challenge with ease by implementing dynamic height UIWebView in the UITableView as shown below.

Download Source

webView2

Steps to add Dynamic height UIWebView to UITableView

Step 1 : 

Create a Navigation View controller and  add two buttons to the ViewController in order to differentiate between the dynamic multi-media contents as shown below

Dynamic height UIWebView

In the .h of the ViewController create an action for the button, as the code shown below.

 

Step 2 :

In the .m of the ViewController, add the function for the button action. In order to display the multimedia contents we are creating a new ViewController and name it as WebTableViewController

Before showing the contents in the UIWebView, we can style the contents as per our wish by using the below code snippet

It’s time to add function to the button action like the code shown below.

 Step3 : 

Let’s create some getter and setters , UiTableView and also create a Custom UITableViewCell in the WebTableViewController.h as shown below

 

Step 4 : 

In the .m of the WebTableViewController add the datasource methods of the UITableView like

  • - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  • - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  • - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

In the cellForRowAtIndexPath add the custom cell and calculate the height of the html content using the code given below

Then set the property of the UIWebView and add it to the CustomCell as shown below.

 

Step 4 :

The Trick to calculate and the update the dynamic height of WebView in UITableView lies in this small snippet of code

 

Step 5 :

Build and Run the above source code, Bingo and result is shown as below .

 

Screen Shot 2014-01-12 at 7.49.02 PM

 

Customise the content as per your needs and add desired functions to explore more.. such as detecting the image content in the webview and intercept the link and open in the customised browser etc….

That’s it from this tutorial and see you again with more exciting stuff.

 
Download Source

Tagged with: