iOS App开发中使用及自定义UITableViewCell的教程

2020-01-15 14:42:22王振洲

    if (cell == nil) { 
        cell = [[UITableViewCell alloc] 
                initWithStyle:UITableViewCellStyleDefault 
                reuseIdentifier:TableSampleIdentifier]; 
    } 
    
    NSUInteger row = [indexPath row]; 
    cell.textLabel.text = [listData objectAtIndex:row]; 
 return cell; 
}


上面的第二个方法中,
复制代码
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];
这个语句根据标识符TableSampleIdentifier寻找当前可以重用的UITableViewCell。当某行滑出当前可见区域后,我们重用它所对应的UITableViewCell对象,那么就可以节省内存和时间。
如果执行词语后,cell为nil,那我们再创建一个,并设置去标识符为TableSampleIdentifier:
复制代码
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
这里UITableViewCellStyleDefault是表示UITableViewCell风格的常数,除此之外,还有其他风格,后面将会用到。
注意参数(NSIndexPath *)indexPath,它将行号row和部分号section合并了,通过[indexPath row];获取行号。之后给cell设置其文本:
复制代码
cell.textLabel.text = [listData objectAtIndex: row];
6、运行一下:

 

iOS,App开发,UITableViewCell

7、给每一行添加图片:
7.1 将图片资源添加到工程:拖到工程中,前面的文章有提到。
7.2 在cellForRowAtIndexPath方法的return语句之前添加代码:

复制代码
UIImage *image = [UIImage imageNamed:@"blue.png"]; 
cell.imageView.image = image; 
UIImage *highLighedImage = [UIImage imageNamed:@"yellow.png"]; 
cell.imageView.highlighedImage = highLighedImage;
7.3 运行,效果如下:

 

iOS,App开发,UITableViewCell