UITableViewCell. Как мне просто выделить ячейку во время касания?

У меня есть пользовательский tableViewCell. Я хочу указать, что пользователь приземлился, выделив. Стиль выделения ячеек — UITableViewCellSelectionStyleBlue. В родительском контроллере я установил self.clearsSelectionOnViewWillAppear = YES.

Я должен быть готов идти. Неа. Выбор по-прежнему прилипает к ячейке. То, что я хочу, это индикация выбора только на время приземления. Внешний вид должен немедленно вернуться к невыбранному внешнему виду при ретуши.

Как мне это сделать?

С уважением,
Дуг


person dugla    schedule 01.05.2012    source источник


Ответы (5)


В приведенном ниже примере Swift используется didHighlightRowAtIndexPath для изменения цвета фона ячейки при касании и didUnhighlightRowAtIndexPath для сброса цвета — см. ниже:

// MARK: UITableViewDelegate

func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
  if let cell = tableView.cellForRowAtIndexPath(indexPath) {
     cell.backgroundColor = UIColor.greenColor()
  }
}

func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
  if let cell = tableView.cellForRowAtIndexPath(indexPath) {
     cell.backgroundColor = UIColor.blackColor()
  }
}
person Zorayr    schedule 14.05.2015
comment
это не работает. Цвет не сбрасывается при прикосновении - person Dalton Sweeney; 09.03.2017
comment
Можете ли вы поставить точку останова в didUnhighlightRowAtIndexPath: и подтвердить, что она вызывается при исправлении? Если вы можете подтвердить это, то следующим виновником может быть ваша логика изменения цвета. - person Zorayr; 09.03.2017
comment
извините, я понял, что моя проблема заключалась в том, что в моей раскадровке были выбраны «задержки касания контента». - person Dalton Sweeney; 09.03.2017

перезаписать - (void)setSelected:(BOOL)selected animate:(BOOL)animated без вызова super

person Jonathan Cichon    schedule 01.05.2012
comment
Ячейка выбирается только после касания - вопрос хочет изменить цвет при касании. - person Zorayr; 14.05.2015
comment
Override - (void) setHighlighted: (BOOL) выделенная анимация: (BOOL) анимация без вызова super - person King Tech; 05.04.2020

Это работает:

Он получает фоновое изображение с границей ячейки, похожей на разделитель. Не изменяйте настройки таблицы по умолчанию в построителе интерфейса. Убедитесь, что для UITableViewCellSelectionStyleNone НЕ установлено значение selectionstyle. Вставляю рабочий код. :

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *kCellIdentifier = @"PlayListCell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier];
}
MPMediaPlaylist *playList = [playlistCollection objectAtIndex:indexPath.row];
cell.textLabel.text = playList.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
 // cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d Songs",[playList.items count]];
MPMediaItemCollection *playListMediaCollection = [playlistCollection objectAtIndex:indexPath.row ];

cell.imageView.image =[UIImage imageWithCGImage:[self getImageForCollection:playListMediaCollection.items]];

// the main code which make it highlight

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:170.0f/255.0 green:170.0f/255.0 blue:170.0f/255.0 alpha:1.0f];
[bgColorView.layer setBorderColor:[UIColor blackColor].CGColor];
[bgColorView.layer setBorderWidth:1.0f];
[cell setSelectedBackgroundView:bgColorView];


return cell;

}

person Ankish Jain    schedule 30.12.2014

У меня была та же проблема. Приведенный ниже код отлично сработал.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
person Rohit Ranjan Pandey    schedule 01.05.2012
comment
Вы действительно хотите перезагружать таблицу при каждом касании? Это абсолютно неправильный способ сделать тему. - person surfrider; 28.08.2014
comment
Это делает ячейку синей, но она остается такой и работает только на touchUpInside. А если только приземлиться? - person Ethan Parker; 16.01.2015
comment
Ячейка помечается выбранной только после касания - вопрос хочет изменить цвет при касании вниз; плюс, я согласен с @surfrider, зачем перезагружать данные? - person Zorayr; 14.05.2015

person    schedule
comment
У нас есть победа! Для тех, кто дома, фактическая сигнатура метода — deselectRowAtIndexPath:animated:. Сладкий. Ваше здоровье. - person dugla; 01.05.2012
comment
Я не могу поверить, что я трачу так много, чтобы решить эту проблему с болью ... Вы просто думаете, что касание какао сделает это в didHighlightItemAtIndexPath в любом случае, спасибо @Dancreek - person andy shih; 04.01.2016