要点是用cellForRowAtIndexPath取cell时,如果取得的是nil,则不用更新这个cell。因为在cell的重用机制下,这个cell在显示时会用新的数据去显示的,所以如果取得nil,则不用处理。
#import "ViewController.h"
@interface Person :NSObject
@property(strong)NSString* name;
@end
@implementation Person
@end
@interface ViewController ()
{
NSArray* _dataSource;
}
@property (weak, nonatomic) IBOutletUITableView *_table;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
NSMutableArray* persons = [NSMutableArrayarray];
for(int i=0;i<20;i++){
Person* person = [Personnew];
person.name = [NSStringstringWithFormat:@"person%d",i];
[personsaddObject:person];
}
_dataSource = [NSArrayarrayWithArray:persons];
[self._tablereloadData];
}
- (IBAction)changeAction:(id)sender {
//修改可见的cell
{
NSInteger index = 1;
Person* person = (Person*)_dataSource[index];
person.name = [NSStringstringWithFormat:@"change%ld",(long)index];
NSIndexPath* myIndexPath =[NSIndexPathindexPathForRow:index inSection:0];
UITableViewCell* cell = [self._tablecellForRowAtIndexPath:myIndexPath];
//没有取到,则说明这个cell没有显示,在滚动显示,会用重用机制显示更改后的内容。
if(cell){
cell.textLabel.text = person.name;
}
}
//修改不可见的cell
{
NSInteger index = 9;
Person* person = (Person*)_dataSource[index];
person.name = [NSStringstringWithFormat:@"change%ld",(long)index];
NSIndexPath* myIndexPath =[NSIndexPathindexPathForRow:index inSection:0];
UITableViewCell* cell = [self._tablecellForRowAtIndexPath:myIndexPath];
//没有取到,则说明这个cell没有显示,在滚动显示,会用重用机制显示更改后的内容。
if(cell){
cell.textLabel.text = person.name;
}
}
//修改不可见的cell
{
NSInteger index = 12;
Person* person = (Person*)_dataSource[index];
person.name = [NSStringstringWithFormat:@"change%ld",(long)index];
NSIndexPath* myIndexPath =[NSIndexPathindexPathForRow:index inSection:0];
UITableViewCell* cell = [self._tablecellForRowAtIndexPath:myIndexPath];
//没有取到,则说明这个cell没有显示,在滚动显示,会用重用机制显示更改后的内容。
if(cell){
cell.textLabel.text = person.name;
}
}
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return_dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* CellIdent =@"cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdent];
if (cell == nil) {
cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdent];
}
Person* person = (Person*)_dataSource[indexPath.row];
cell.textLabel.text = person.name;
cell.accessoryType =UITableViewCellAccessoryNone;
return cell;
}