Пользовательское редактированиеAccessoryView не работает - PullRequest
7 голосов
/ 04 сентября 2011

У меня есть следующий код для UITableView с пользовательской ячейкой:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FolderCellViewController"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"FolderCellViewController" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
        cell.editingAccessoryView=accessoryView; //accessoryView is a UIView within a UITableViewCell, and it is properly connected in IB
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return NO; //YES here makes a red delete button appear when I swipe
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        // [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

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

РЕДАКТИРОВАТЬ: Видимо, то, что я сделал, устанавливает стиль редактирования только тогда, когда вся таблица находится в режиме редактирования, а некогда я проведу по каждой отдельной клетке.Так что я хочу сделать, когда я проведу пальцем по каждой ячейке, для этой ячейки появится специальный accessoryView.Но я не уверен, как это сделать ..

1 Ответ

10 голосов
/ 04 сентября 2011

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

Чтобы показать это как при входе в режим редактирования всей таблицы, так и при перелистывании отдельной строки, у меня естьВ моем подклассе UITableViewController реализовано следующее:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    if (editing)
        self.editingFromEditButton = YES;
    [super setEditing:(BOOL)editing animated:(BOOL)animated];
    self.editingFromEditButton = NO;
    // Other code you may want at this point...
}

editingFromEditButton - это свойство BOOL подкласса.Этот метод вызывается при нажатии стандартной кнопки «Редактировать».Он используется в следующем методе, который предотвращает отображение стандартной кнопки удаления:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editingFromEditButton)
        return UITableViewCellEditingStyleNone;

    // Otherwise, we are at swipe to delete
    [[tableView cellForRowAtIndexPath:indexPath] setEditing:YES animated:YES];
    return UITableViewCellEditingStyleNone;
} 

Если для представления всей таблицы установлен режим редактирования, то каждой ячейке также будет отправлено сообщение setEditing.Если мы прокрутили одну строку, нам нужно перевести эту ячейку в режим редактирования, а затем вернуть стиль UITableViewCellEditingStyleNone, чтобы предотвратить появление стандартной кнопки удаления.

Затем, чтобы закрыть пользовательский аксессуар для редактирования, вам также понадобится следующий код:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    // Cancel the delete button if we are in swipe to edit mode
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.editing && !self.editing)
    {
        [cell setEditing:NO animated:YES];
        return;
    }

    // Your standard code for when the row really is selected...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...