ios-dynamically adjusts the height of the UITableViewCell

Source: Internet
Author: User

os-dynamically adjusts UITableViewCell's highly developed documentation for iOS , by the Friends League translation group Stefaliu.

At first glance, it is not easy to adjust the height dynamically, and the first idea that is intended to solve it is often incorrect. In this article I will show how to make the height of a chart cell dynamically change according to the contents of the text inside, without having to subclass the UITableViewCell. You can certainly do this by subclasses, but doing so makes the code complex because the setting height is on the instance of the chart itself rather than on the cell. Below you will see that this is actually a very easy thing to do. For a chart to be able to dynamically adjust the height is a very meaningful thing, I first think of the need for this function is when the column length will change the text list, if the text content is less, it may be suitable for normal cell label, but if the text is longer, You have to reset the cell size to make it easier to display all the text content. I summed up the main steps to reset the cell size as follows:

1 Create and add a UILabel as a child view of cell cells; 2 Delegate method in UITableView: (cgfloat)tableView:(uitableview*) TableViewheightforrowatindexpath: (Nsindexpath *) indexpath calculation of height 3 in UITableView delegate method: ( UITableViewCell*)tableView:(uitableview*)tableViewcellforrowatindexpath: ( Nsindexpath *) calculates the box size of the UILabel in Indexpath.

Let me go through these steps in more detail, first look at the program output: In a normal chart, you can simply set the text content of a label in a cell using the following method:

[[Cell Textlabel] setText:@"Text for the current cell here." ];

You might think that you can take full control of UILabel , but I find that any attempt to change the size of the UILabel box fails, so this is not a good candidate for dynamic resizing.

We need to design a UILabel and then add it to the contents view of the cell. To implement it needs to call-Cellforrowatindexpath, the approximate content is as follows:

1234567891011121314151617181920
-(UITableViewCell*) TableView:(UITableView*) TV Cellforrowatindexpath:(Nsindexpath*) Indexpath{UITableViewCell*cell; UILabel*label=Nil Cell=[TV Dequeuereusablecellwithidentifier:@"Cell"];If(cell==Nil){cell=[[[UITableViewCell Alloc] initWithFrame: Cgrectzero Reuseidentifier:@"Cell"] Autorelease]; Label=[[UILabel Alloc] initWithFrame: Cgrectzero];[Label Setlinebreakmode: Uilinebreakmodewordwrap];[Label Setminimumfontsize: font_size[label setnumberoflines: 0[label setfont:[ Uifont systemfontofsize:font_size]]; [label settag:1];  [[cell Contentview :label}             

This is not the complete code because we initialize its label only when we create the cell, which corresponds to the if (cell = = nil) of the judgment module after calling-dequeuereusablecellwithidentifier. Here I would like to highlight two points: the first one, we can notice that the label has a tag corresponding to it, because the call to-settag:1. This tag can be used when the cell is not equal to nil. 2nd, we add the label to the contents view of the cell by calling [[cell Contentview] Addsubview:label], which is only used when the label is initialized. Each call to this function adds a label to the child view sequence. We'll add this code to the complete section below, but let's look at how to set the cell's height.

Calculate the cell's height

In a complex cell, it can be difficult to calculate heights, but you just need to be concerned about the parts that are highly variable. In my case, the only thing that needs to be dealt with is the label added to the cell. We calculate the height of the cell based on the size of the text, and the size of the text depends on the length of the text and the text font. The NSString class provides the function-sizewithfont to make it easier for us to get the cell size. The following code describes the function-heightforrowatindexpath:

123456789101112
-(CGFloat) TableView:(UITableView*) TableView Heightforrowatindexpath:(Nsindexpath*) Indexpath;{NSString*text=[Items Objectatindex:[Indexpath Row]]; Cgsize constraint= Cgsizemake(Cell_content_width-(Cell_content_margin*2), 20000.0f);  cgsize size = [ Text Sizewithfont:[uifont Systemfontofsize:font_size:constraint Linebreakmode:uilinebreakmodewordwrap];  CGFloat height = max (Size.Height, 44.0f);  return height +  (Cell_content_margin * 2);              /span>       

You will notice that we have used several constants to calculate the size of the cell, which are defined as follows:

#define FONT_SIZE 14.0f#define Cell_content_width 320.0f#define Cell_content_margin 10.0f 

The constant cell_content_width is the width of the entire cell. Cell_content_margin is the page margin we define, and font_size is the font size we use for text.

First we want to create a constraint on the content width. The first parameter of the Cgsizemake is the total content width minus two margin margins. Because there is a margin blank on the left and right sides. The second parameter is the maximum value we provide. This constraint will be used in the subsequent function-sizewithfont. In-sizewithfont we set it to Uilinebreakmodewordwrap to get the correct size in case of allow wrapping and the constraints mentioned above. Finally, we use the Max macro to set the cell's height and ensure that the cell's height is no less than 44 pixels because it returns a size. The maximum value in height and 442 numbers. Finally, we take the upper and lower margins into account to get the final result.

To make the reader visualize the margins, one can see that there is a boundary around the label. call [[Label layer] setborderwidth:2.0f] to display the boundary so that we can see the margins blank. Calculate and set the UILabel box size

The method we used to calculate the height in front is also the way we use to set the size of the UILabel box. The following-Cellforrowatindexpath code complements the complete:

123456789101112131415161718192021222324252627282930313233343536
-(UITableViewCell*) TableView:(UITableView*) TV Cellforrowatindexpath:(Nsindexpath*) Indexpath{UITableViewCell*cell; UILabel*label=Nil Cell=[TV Dequeuereusablecellwithidentifier:@"Cell"];If(cell==Nil){cell=[[[UITableViewCell Alloc] initWithFrame: Cgrectzero Reuseidentifier:@"Cell"] Autorelease]; Label=[[UILabel Alloc] initWithFrame: Cgrectzero];[Label Setlinebreakmode: Uilinebreakmodewordwrap];[Label Setminimumfontsize: font_size];[Label Setnumberoflines:0];[Label SetFont:[Uifont systemfontofsize: font_size]];[Label Settag:1];[[Label Layer] Setborderwidth: 2.0f];[[Cell Contentview] Addsubview: Label];}NSString*text=[Items Objectatindex:[Indexpath Row]]; Cgsize constraint= Cgsizemake(Cell_content_width-(Cell_content_margin*2), 20000.0f); Cgsize size=[Text Sizewithfont:[Uifont systemfontofsize: font_size] Constrainedtosize: Constraint Linebreakmode: Uilinebreakmodewordwrap];If(!label) label=(UILabel*)[cell viewwithtag:1< Span style= "color: #002200;" >];  [label settext:text [label setframe:cgrectmake  (Cell_content_margin, Cell_content_margin, cell_content_width - (Cell_content_margin * 2 (Size.Height, 44.0f) ) ];  return cell;              /span>        

Note that the if (cell = = nil) module is an initialization code that runs only once when the cell is created. The external code of the module is executed every time as long as the-Cellforrowatindexpathis called after each data Update or window drag.

In other words, you need to set the label text content and set the label box size each time. Note If the label is in an uninitialized state, we need to get a handle to the UILabel by calling [cell Viewwithtag:1]. This code is basically the same as the code for the previous height calculation.

Summarize

It is not difficult to dynamically calculate cell cell height. If you have a complex cell, you only need to determine the cell's height based on the width of the content and the size of the specific text font. If you don't know where your frame is, you just need to make the frame visible by calling [[view Layer] setborderwidth:2.0f]. This will help you understand the drawing process and understand the problem of drawing display more quickly and at a deeper level.

Demo Project file:dynamicheights Demo Project

Matt Long original link:http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/

ios-dynamically adjusts the height of the UITableViewCell

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.