IOS-dynamically adjust the UITableViewCell height and uitableviewcell height

Source: Internet
Author: User
Tags blank page

IOS-dynamically adjust the UITableViewCell height and uitableviewcell height

OS-dynamically adjust the height of UITableViewCellIOS development documentation, by umeng translation team stefaliu.

At first glance, it seems that dynamic height adjustment is not easy, and the first idea to solve it is often incorrect. In this article, I will show how to make the height of the chart cell dynamically change according to the text content, without the need to subclass UITableViewCell. Of course you can implement it by subclass, but this will make the code complicated because the height is set on the instance of the chart rather than on the cell. Next, you will see that this is actually a breeze. It makes sense to dynamically adjust the height of a chart. The first thing I want to think of is to display a list of texts with varying lengths, if the text content is small, it may be suitable for the normal cell label, but if the text gets longer, you have to reset the cell size to display all the text content. I have summarized the main steps to reset the cell size as follows:

1. Create and add a UILabel as a sub-view of the cell. 2. Delegate method in UITableView: (CGFloat) tableView :( UITableView *) tableViewHeightForRowAtIndexPath: (NSIndexPath *) Height Calculation in indexPath 3 delegate method in UITableView: (UITableViewCell *) tableView :( UITableView *) tableViewCellForRowAtIndexPath: (NSIndexPath *) the box size of UILabel is calculated in indexPath.

Next I will introduce these steps in detail. First, let's take a look at the program output: In a common chart, you can simply set the text content of the label in the cell using the following method:

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

Maybe you think this will allow you to completely control UILabel, but I found that any attempt to change the size of the UILabel box failed, therefore, this is not a good candidate for dynamic resizing.

We need to design a UILabel and add it to the cell content view. To implement it, you need to call-cellForRowAtIndexPath. The general 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] addSubview:label];  }}

This is not the complete code because we only initialize its label when creating a cell. This Code corresponds to the judgment module if (cell = nil) after calling-dequeueReusableCellWithIdentifier ). Here I want to emphasize two points: first, we can note that there is a label corresponding to the label, because-setTag: 1 is called. This label can be used when cell is not equal to nil. Second, we call [[cell contentView] addSubview: label] to add the label to the cell content view, which is only used during label initialization. Each time this function is called, a label is added to the subview sequence. We will complete the code below, but let's take a look at how to set the height of the cell.

Calculate the cell height

In a complex cell, it may be difficult to calculate the height, but you only need to care about the components whose height will change. In my example, the only thing that needs to be processed is the label added to the cell. We calculate the cell height based on the text size, and the text size depends on the text length and text font. The NSString class provides the function sizeWithFont to help us obtain the cell size. The following Code introduces 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] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];   CGFloat height = MAX(size.height, 44.0f);   return height + (CELL_CONTENT_MARGIN * 2);}

You will notice that several constants are used to calculate the cell size. Their definitions are as follows:

#define FONT_SIZE 14.0f#define CELL_CONTENT_WIDTH 320.0f#define CELL_CONTENT_MARGIN 10.0f

The constant CELL_CONTENT_WIDTH indicates the width of the entire cell. CELL_CONTENT_MARGIN is the blank page and FONT_SIZE is the font size of the text.

First, we need to create a content width constraint. The first parameter of CGSizeMake is the total content width minus two blank pages. There is a blank page on the left and right. The second parameter is the maximum value we provide. This constraint will be used in the following function-sizeWithFont. In-sizeWithFont, we set it to UILineBreakModeWordWrap to get the correct size when automatic line breaks are allowed and the constraints mentioned above. Finally, we use the MAX macro to set the cell height, and ensure that the cell height is not less than 44 pixels, because it returns the maximum values of size. height and 44. Finally, we will take the upper and lower page blank into consideration to get the final result.

In order to make readers understand the blank page visually, the following one can see that there is a border around the label. Call [[label layer] setBorderWidth: 2.0f] to display the border so that we can see the blank page. Calculate and set the UILabel box size

The previous method we used to calculate the height is also the method we used to set the UILabel box size. Below we will complete the-cellForRowAtIndexPath code:

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];   [label setText:text];  [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];   return cell;}

Note that the if (cell = nil) module is the initialization code and runs only once when the cell is created. The external code of this module is executed every time. After each data update or window dragging, the-cellForRowAtIndexPath is called.

That is to say, you need to set the text content in the label and the size of the label outer box each time. Note: If the label is not initialized, call [cell viewWithTag: 1] to obtain the UILabel handle. This section of code is basically the same as the previous code that calculates the height.

Summary

It is not difficult to calculate the height of a cell dynamically. If you have a very complex cell, you only need to determine the height of the cell Based on the Content width and the size of the specific text font. If you do not know where your external box is displayed, you only need to call [[view layer] setBorderWidth: 2.0f] to display the external box. This will help you understand the drawing process and more quickly understand the problem of drawing display at a deeper level.

Demo Project file: DynamicHeights Demo Project

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

Related Article

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.