struggling with formatting dynamic row height in UITableView

后端 未结 3 1243
清歌不尽
清歌不尽 2021-02-06 18:30

I am trying to resize the height of my row in UITableView based on the text length. I have the following code:

- (CGFloat)tableView:(UITableView *)tableView heig         


        
3条回答
  •  醉话见心
    2021-02-06 19:20

    Instead of subclassing as suggested by others, you could also add your own subviews to the cell’s content view.

    From Customizing Cells:

    If you want the cell to have different content components and to have these laid out in different locations, or if you want different behavioral characteristics for the cell, you have two alternatives. You can add subviews to the contentView property of the cell object or you can create a custom subclass of UITableViewCell.

    • You should add subviews to a cell’s content view when your content layout can be specified entirely with the appropriate autoresizing settings and when you don’t need to modify the default behavior of the cell.
    • You should create a custom subclass when your content requires custom layout code or when you need to change the default behavior of the cell, such as in response to editing mode.

    See this example:

    #define CUSTOM_IMAGE_TAG 99
    #define MAIN_LABEL 98
    
    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *CellIdentifier = @"Cell";
        UIImageView *customImageView = nil;
        UILabel *mainLabel = nil;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            customImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)] autorelease];
            customImageView.tag = CUSTOM_IMAGE_TAG;
            [cell.contentView addSubview:customImageView];
    
            mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(60.0f, 10.0f, 100.0f, 21.0f)] autorelease];
            mainLabel.tag = MAIN_LABEL;
            mainLabel.numberOfLines = 0;
            [cell.contentView addSubview:mainLabel];
        } else {
            customImageView = (UIImageView *)[cell.contentView viewWithTag:CUSTOM_IMAGE_TAG];
            mainLabel = (UILabel *)[cell.contentView viewWithTag:MAIN_LABEL];
        }
    
        // Configure the cell.
        CGRect frame = mainLabel.frame;
        frame.size.height = ... // dynamic height
        mainLabel.frame = frame;
    
        return cell;
    }
    

    Obviously, you still need to implement tableView:heightForRowAtIndexPath:.

提交回复
热议问题