全面解析iOS应用中自定义UITableViewCell的方法

2020-01-15 13:30:04王振洲

如果还有其他控件,比如UIButton等等,也是一样的。

这些控件在实例化的时候,设置frame为CGRectZero, 然后分别计算各自的高度和尺寸

使用cell.contentview addSubview 的方式,将这些子空间添加到cell中。重新计算cell的frame时

也需要把这些控件的frame累加上。上代码:

复制代码
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
  
    static NSString *CellIdentifier = @"Cell";  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
      
    if (cell == nil) {  
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;  
          
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];  
        label.tag = 1;  
        label.lineBreakMode = NSLineBreakByCharWrapping;  
        label.highlightedTextColor = [UIColor whiteColor];  
        label.numberOfLines = 0;  
        label.opaque = NO; // 选中Opaque表示视图后面的任何内容都不应该绘制  
        label.font=[UIFont systemFontOfSize:12.0f];  
        label.backgroundColor = [UIColor grayColor];  
        [cell.contentView addSubview:label];  
          
        UIButton *tmpButton=[[UIButton alloc]initWithFrame:CGRectZero];  
        tmpButton.tag=2;  
        tmpButton.backgroundColor=[UIColor cyanColor];  
        [cell.contentView addSubview:tmpButton];  
        tmpButton.opaque=NO;  
        [tmpButton setTitle:@"nihao" forState:UIControlStateNormal];  
        [tmpButton setTitleColor:[UIColor whiteColor ]forState:UIControlStateHighlighted];