0

Наверное, простое исправление.Change Table View Cell's UIImage on Tap

У меня есть изображение внутри каждой ячейки моего контроллера табличного вида и распознавателя жестов. Это нормально работает и регистрируется.

Мне нужно, чтобы изображение изменилось с его состояния по умолчанию, чтобы переключиться между «выбранным» состоянием (зеленый) и «отмененным» состоянием (красный). Другими словами, это контрольный список, который сначала серый, затем вы нажимаете изображение, изображение поворачивается на зеленую галочку, снова нажимает, оно превращается в красный x.

Вот этот улов: если это работает только в условном выражении в методе didSelectRowAtIndexPath, но поскольку я добавил распознаватель жестов и создал метод imageTapped, я не могу его перевести. Поэтому в противном случае полезные темы, такие как this, не работают для меня.

Спасибо, что и всегда. Вы, ребята, самые лучшие.

Вот код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"PlacesCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PlacesCell"]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    //Create ImageView 
    cell.imageView.image = [UIImage imageNamed:@"checkmark.png"]; 

    //Add Gesture Recognizer 
    UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped)]; 
    tapped.numberOfTapsRequired = 1; 
    [cell.imageView addGestureRecognizer:tapped]; 
    cell.imageView.userInteractionEnabled = YES; 
    [cell addSubview:cell.imageView]; 

    return cell; 

    } 

//Method controlling what happens when cell's UIImage is tapped 
-(void)imageTapped 
{ 

    UITableViewCell *cell; 

    UIImage *imageDefault = [UIImage imageNamed:@"checkmark.png"]; 
    UIImage *imageRed = [UIImage imageNamed:@"checkmark(red).png"]; 
    UIImage *imageGreen = [UIImage imageNamed:@"checkmark(green).png"]; 

    if (cell.imageView.image == imageDefault) { 
     cell.imageView.image = imageGreen; 
     cell.selected = true; 
     NSLog(@"Selected"); 
    } else { 
     cell.imageView.image = imageRed; 
     cell.selected = false; 
     NSLog(@"Deselected"); 
    } 
} 

ответ

4

я модифицировал свой код, проверить его

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"PlacesCell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PlacesCell"]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
} 

//Create ImageView 
cell.imageView.image = [UIImage imageNamed:@"checkmark.png"]; 

//Add Gesture Recognizer 
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)]; 
tapped.numberOfTapsRequired = 1; 
[cell.imageView addGestureRecognizer:tapped]; 
cell.imageView.userInteractionEnabled = YES; 
//[cell addSubview:cell.imageView]; 

return cell; 

} 

//Method controlling what happens when cell's UIImage is tapped 
-(void)imageTapped:(UIGestureRecognizer*)gesture 
{ 

UIImageView *selectedImageView=(UIImageView*)[gesture view]; 

UIImage *imageDefault = [UIImage imageNamed:@"checkmark.png"]; 
UIImage *imageRed = [UIImage imageNamed:@"checkmark(red).png"]; 
UIImage *imageGreen = [UIImage imageNamed:@"checkmark(green).png"]; 

if (selectedImageView.image == imageDefault) { 
    selectedImageView.image = imageGreen; 
    //cell.selected = true; 
    NSLog(@"Selected"); 
} else { 
    selectedImageView.image = imageRed; 
    //cell.selected = false; 
    NSLog(@"Deselected"); 
} 
} 
+0

отлично работает! Спасибо @pawan! – jeremytripp

Смежные вопросы