您的位置:首页 > 其它

数据源变更时,table中更新对应cell的显示

2015-04-10 14:27 183 查看
要点是用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐