zoukankan      html  css  js  c++  java
  • [转]让UITableView中的单元格根据内容的多少自动调整高度


    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; { NSString *text = [items objectAtIndex:[indexPath row]];
    //下句中
    (CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2) 表示显示内容的label的长度 ,20000.0f 表示允许label的最大高度
        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);
    }
    
    - (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;
    
    }

    源代码下载:http://download.csdn.net/detail/ygm900/5404317

    以上源代码可在模拟器模式下正常运行,已测试。

  • 相关阅读:
    Will Go eventually replace C++ as Google hoped when Go came out?
    5G到底什么时候来,它究竟能给我们带来什么?
    eog——Eye of GNOME Image Viewer
    Appweb——Embedded Web Server
    【2017】数字重排
    【9203】众数
    【2034】四人投票
    【9204】第k小整数
    【2031】求一元三次方程的解
    iOS 7: 如何为iPhone 5s编译64位应用
  • 原文地址:https://www.cnblogs.com/ygm900/p/3086246.html
Copyright © 2011-2022 走看看