2015-01-17

Using dynamic height image/content with UITableViewCell

Views: 5748 | Add Comments

The UITableViewCell itself is not dynamic height, it never knows its height, the UITableView containing it asks UITableViewDatasource for its height. If you want to support dynamic height cells, you have to force UITableView to ask for the height of a cell just after the cell’s height changed.

So, for your iOS App to use UITableViewCell with dynamic height, you have to follow these two steps:

  1. Return a default height when UITableView first time ask for cell’s height.
  2. After the cell is layed out(UIView’s layoutSubviews method executed), tell the UITableView to reload the cell, so it will ask the cell’s height for the second time.

This is not an easy task, because the cell has to concern about the modification of it’s subviews, no matter the subview is type of UILabel, UIImageView, UIButton, or other custom UIView. So the cell becomes too complicated and not reusable.

It is a waste of time, it is doing the same thing over and over again, every programmer should never bear it! Things have to be changed! If Apple don’t change it, I will!

With CocoaUI‘s powerful auto layout(flow layout) feature, you don’t have to worry about UI controls’ width and height it you choose not to. You want a label, OK, just add it into CocoaUI’s IView and set that label with a text, CocoaUI will calculate the width and heigth of the label, layout it on the proper position. If you want an image control with image loaded from network, sure, just add the image into IView, set the image src just like you do with Web, CocoaUI will load the image from network, determine the size of the image, layout it right.

IView will update its width and height every time its sub controls are layouted and rendered, and then update the wrapping UITableViewCell. Which means you will see your iPhone App’s content auto grows.

I will show some code.

ITable *table = [[ITable alloc] init];
[table addIView:[ILabel labelWithText:@"first line"]];
[table addIView:[ILabel labelWithText:@"first line\nsecond line"]];

After this code executed, you will see a table with two rows, the second row is two times the height of the first row, because the the second row contains two lines of text, and the first row contains only one line of text.

A dynamic height table cell is as easy as above.

CocoaUI is a powerful iOS UI framework. With CocoaUI, you get the power of:

  • Flow Layout(real Auto Layout) of UI controls.
  • App UI scrollable as Web page.
  • Define native iOS App’s appearance with XML and simple CSS properties.

UI development is usually 30% ~ 50% of Objective-C programming work, with CocoaUI, it is 1% ~ 5%, iOS developers are set free from stupid Apple-style UI coding, they can put more time to strenthen their Apps’ functionalities.

Posted by ideawu at 2015-01-17 12:35:08 Tags: ,

Leave a Comment