2014/10/29

[Objective-C][iOS]UITableViewCellのcellの再利用について

UITableViewCellを使って以下のようにプログラムを組む時があります。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if(cell == nil){
    cell = [UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    
  }

  UIView *view;
  [cell.contentView addSubview:view];
  return cell;
}
これだと、cellごとにUIView *viewが違う場合
ex)
row = 0の時、UISwitch
row = 1の時、UIButton
row = 2の時、UILabel

の時は、再利用すると大変なことになるので、下のように組み直したらうまくいった。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld",(long)indexPath.row];
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if(cell == nil){
    cell = [UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    
  }

  UIView *view;
  [cell.contentView addSubview:view];
  return cell;
}
ただ、この方法でも100行とか行がたくさんあると成立しないので、注意が必要です。

0 コメント:

コメントを投稿