Скрыть метку в TableViewCell, когда удаляешь - PullRequest
3 голосов
/ 07 марта 2012

Я хочу иметь возможность скрыть метку в моем UITableViewCell, чтобы он не перекрывался с заголовком всякий раз, когда пользователь удаляет ячейку.

Я использую следующий код дляинициировать и обработать пролистывание для удаления:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        [self.tableView beginUpdates]; // Avoid  NSInternalInconsistencyException

        // Delete the project object that was swiped
        Project *projectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
        NSLog(@"Deleting (%@)", projectToDelete.name);
        [self.managedObjectContext deleteObject:projectToDelete];
        [self.managedObjectContext save:nil];

        // Delete the (now empty) row on the table
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [self performFetch];

        [self.tableView endUpdates];
    }
}

Я назначил метку в ячейке, используя:

UILabel *projectDate = (UILabel *)[cell viewWithTag:3];
    projectDate.text = project.dateStarted;

И попытался просто установить

projectDate.hidden = YES; 

Однако это не работает.

1 Ответ

6 голосов
/ 07 марта 2012

Я думаю, вам нужно создать подкласс UITableViewCell для реализации этого. В подклассе переопределить - (void) setEditing:(BOOL)editing animated:(BOOL)animated. В этом методе вы можете скрыть метку. Если вам нужно только скрыть метку для операций удаления, используйте self.editingStyle, чтобы условно скрыть метку в зависимости от стиля редактирования (aka: UITableViewCellEditingStyleDelete).

Вот два примера. Я предпочитаю пример два, это проще. Но первый пример позволит вам заменить текст, который может быть полезен:

@implementation CellSubclass{
    NSString *_labelText; //only used in example 1
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
// Example 1, replacing the text value
- (void) setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if (editing && self.editingStyle == UITableViewCellEditingStyleDelete){
        UILabel *label = (UILabel *)[self viewWithTag:3];
        _labelText = label.text;
        self.textLabel.text = nil;
    }  else if (!editing && _labelText){
        UILabel *label = (UILabel *)[self viewWithTag:3];
        label.text = _labelText;
    }
}

//Example 2 - hiding the view itself
- (void) setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if (editing && self.editingStyle == UITableViewCellEditingStyleDelete){
        [self viewWithTag:3].alpha = 0.0f;
    } else {
        [self viewWithTag:3].alpha = 1.0f;
    }
}

@end

Пожалуйста, обратите внимание, что у меня есть два метода с одинаковым именем. Это, очевидно, большое нет-нет .... используйте только один из них.

Также обратите внимание, что я проигнорировал анимированный параметр. Если вы хотите, чтобы исчезновение вашего ярлыка было анимировано во втором примере (иначе ... исчезать / исчезать), все, что вам нужно сделать, это окружить ваши изменения в анимационном блоке, например:

        [UIView animateWithDuration:.3f animations:^{
            [self viewWithTag:3].alpha = 0.0f;
        }]; 

Не думаю, что вы можете оживить первый пример.

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