0

I have a custom UITableView that has 2 types of cells. One cell is just set to toggle between a normal accessory of type checkmark. Another cell is set to have a custom image as the accessory type. When selected that accessory image changes to its opposite type, showing an "Selected" or "Unselected" message.

 if (self.selectedIndex == indexPath.row) {
                cell.accessoryView = self.selectedImageView;
            }else
                cell.accessoryView = self.unSelectedImageView;

If it matters the UIImageViews are initialized as follows:

-(UIImageView *)selectedImageView
{
    if (!_selectedImageView) {
        _selectedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Check"]];
    }
    return _selectedImageView;
}
-(UIImageView *)unSelectedImageView
{
    if (!_unSelectedImageView) {
        _unSelectedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noCheck"]];
    }
    return _unSelectedImageView;
}

i saw someone answer this question:UITableCell AccessoryView: Setting accessoryView equal to UIImageView infinite loop

he said :I have figured out the answer on my own but here it is for anyone else who needs it: UIImageViews cannot be shared so a different instantiation of each UIImageView is required for each visible cell. Now you know.

but i don't know why?

Community
  • 1
  • 1
徐天宇
  • 5
  • 2

1 Answers1

0

A UIView can only be a subview of one parent view, so once you have added your UIImageView to one cell you can't add it to any others.

UIImage doesn't have this limitation, so you can modify your code to have selectedImage and unSelectedImage methods along the lines of what you have now or even modify your current methods so that they return a new UIImageView each time.

Paulw11
  • 108,386
  • 14
  • 159
  • 186