Как изменить один UITableViewCell при касании - PullRequest
0 голосов
/ 13 декабря 2011

У меня есть ячейка табличного представления с несколькими изображениями в них.При прикосновении к изображениям они отображают наложение поверх изображения, которое сообщает пользователю, что это изображение было выбрано.

Есть ли способ изменить внешний вид только одного UITableViewCell без необходимости делать [tableView reloadData], что позволило бы мне по-разному стилизовать ячейку в методе делегата источника данных табличного представления.

Ответы [ 2 ]

1 голос
/ 13 декабря 2011

Если вы хотите избежать подклассов, это может быть достигнуто с помощью распознавателей жестов. Ваш вопрос предполагает взаимодействие пользователя Tap and Hold с каждым изображением, которое я реализовал в приведенном ниже коде. Следует помнить один момент: если пользователь нажимает и удерживает, он может не увидеть текст, который вы хотели бы видеть.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"ImageCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (!cell) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}

UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

 UILongPressGestureRecognizer *recognizer2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Ben.png"]];
imageView.frame = CGRectMake(cell.contentView.bounds.origin.x,cell.contentView.bounds.origin.y , 100, 40);
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:recognizer];
[cell.contentView addSubview:imageView];

UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Steve.png"]];
imageView2.frame = CGRectMake(cell.contentView.bounds.origin.x + imageView.frame.size.width + 10,cell.contentView.bounds.origin.y , 100, 40);
imageView2.userInteractionEnabled = YES;
[imageView2 addGestureRecognizer:recognizer2];
[cell.contentView addSubview:imageView2];

[imageView release];
[imageView2 release];
[recognizer release];
[recognizer2 release];

return cell;}



- (void)imageTapped:(id)sender {
    NSLog(@"%@", sender);

    UILongPressGestureRecognizer *recognizer = (UILongPressGestureRecognizer *)sender;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        UILabel *label = [[UILabel alloc] initWithFrame:recognizer.view.bounds];
        label.text = @"Pressed";
        label.backgroundColor = [UIColor clearColor];
        label.tag = 99999;
        label.textColor = [UIColor whiteColor];
        [recognizer.view addSubview:label];
        [label release];
    }
    else {
        [[recognizer.view viewWithTag:99999] removeFromSuperview];
    }
}

Надеюсь, это поможет.

1 голос
/ 13 декабря 2011

Я бы сделал это для создания подкласса UITableViewCell, а затем на tableView:didSelectRowAtIndexPath:, чтобы получить ссылку на ячейку и делать с ней все, что вы хотите (или просто нацелиться на событие касания изображения, если это не выделение).

Возможно, есть и другой способ сделать это без подкласса, но я все время подклассирую UITableViewCell, и это довольно просто сделать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...