How to make a UITableViewCell with different subviews reusable?

后端 未结 4 1743
误落风尘
误落风尘 2020-12-25 10:07

I have a UITableView in which I display, naturally, UITableViewCells which are all of the same class, let\'s call it MyCell. So I have

4条回答
  •  无人及你
    2020-12-25 10:48

    There are a couple of different ways to do this. You need a way to access that subview and reset or change it on reuse.

    1. You could subclass UITableViewCell with your own class of cell that has a property for the train or car view. That way you could access and change that view when the cell is reused.

    2. Assign a different identifier to each type of cell:

    `

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            static NSString *CarCellIdentifier = @"CarCell";
        static NSString *TrainCellIdentifier = @"TrainCell";
            if(indexPath == carCellNeeded) { 
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CarCellIdentifier];
                 if (cell == nil) {
                     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CarCellIdentifier] autorelease]; 
                 [cell addSubview:carView];
            }
            } else if(indexPath == trainCellNeeded){ 
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TrainCellIdentifier];
                    if (cell == nil) {
                      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TrainCellIdentifier] autorelease]; 
                [cell addSubview:trainView];
                 }
            }
          return cell; 
    }
    
    1. Or assign a special tag to that sub view you are adding and when the cell comes back around again to be reused you can access that specific subview by its tag.

提交回复
热议问题