1.没有自定义cell
1.1:如果是继承UITableViewController方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ID = @"MyCell"; // 1) 如果在storyboard中定义有单元格,系统会自动注册,可以不用再判断cell 是否被实例化 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; }
1.2.如果是没有继承UITableViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ID = @"MyCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID]; }
1.3使用类名进行注册
- (void)viewDidLoad { [super viewDidLoad]; // self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 20; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; cell.textLabel.text = [NSString stringWithFormat:@"text-%d", indexPath.row]; return cell; }
2.自定义cell
2.1:如果是继承UITableViewController方法
注意:如果没有注册表格的话,不要用
[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]方法,
要用tableView dequeueReusableCellWithIdentifier:CellIdentifier方法
2.2.1:如果在storyboard和xib中设置cell标识符
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ID = @"MyCell"; // 1) 如果在storyboard中定义有单元格,系统会自动注册,可以不用再判断cell 是否被实例化 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; } —(void)viewload { [tableView registerClass:[ChatCell class] forCellReuseIdentifier:@"myCell"]; } #pragma mark 每一行显示的内容 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // 1. 创建一个静态表格标示字符串,定义静态变量时,变量首字母要大写 static NSString *CellIdentifier = @"myCell"; // 2. 从缓存池查找是否有可用的表格行对象 ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // 3. 如果没有找到可重用单元格对象,实例化新的单元格 // if (cell == nil) { // cell = [[ChatCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; // } }
2.2.2:如果没有设置cell标识符
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ID = @"MyCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID]; }
浙公网安备 33010602011771号