Пользовательский контент uitableviewcell не анимируется при скрытии кнопки удаления
Я хочу знать, что мне не хватает, поскольку моя ячейка не оживляет, скрывая кнопку удаления. Метка возвращается в исходное положение до того, как стирание кнопки завершает анимацию.
Когда я нажимаю круглый вид редактирования, чтобы показать кнопку удаления, анимация метки работает:
![Screenshot of cells where the delete button appears]()
Однако, когда я снова нажимаю его, чтобы скрыть кнопку удаления, движение метки не анимируется:
![Screenshot of cells where the delete button disappears]()
Примечание. Эти снимки экрана не создаются из следующего кода. Но они показывают проблему.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
homeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[homeCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Set up the cell
Consumed *drinkObj = [self.appDelegate.consumedDrinksArray objectAtIndex:indexPath.row];
cell.titleLabel.text = drinkObj.drinkName;
NSString *detailTextTime = [NSDate stringFromDate:drinkObj.dateConsumed withFormat:@"h:mma"];
NSString *detailTextrelative = [relativeDateTransformer transformedValue:drinkObj.dateConsumed];
NSString *detailText = [NSString stringWithFormat:@"%@ %@ ", detailTextTime,detailTextrelative];
cell.timeLabel.text = detailText;
cell.stdDLabel.text = @"999.0"; //[NSString stringWithFormat:@"%@", drinkObj.standardDrinks];
cell.stdDLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
cell.titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
cell.timeLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Ответы
Ответ 1
EDIT:
Я вижу, что ошибка отличается от того, что я понял в первую очередь.
Позвольте исправить мой ответ.
Если я прав, ваша кнопка удаления автоматически исчезнет с анимацией, но просмотр содержимого изменится без анимирования (позади анимации кнопок).
В этом случае вам нужно самому управлять анимацией.
Я даю вам код, предполагающий, что вы не поддерживаете ротацию. Если вы хотите поддерживать ротацию, вам понадобится больше кода: -)
Вот пример проекта (есть много кода, потому что я использовал стандартный шаблон xcode master-detail, смотрю только на пользовательскую ячейку): Пример Проект
Чтобы применить его к вашему коду:
Во-первых, измените маску авторезистентных меток на правой стороне ячейки для привязки на стороне LEFT.
Я не уверен, что правильная метка является stdDLabel, я буду считать ее
// if the right margin is flexible, the left-top-bottom are fixed
cell.stdDLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
В своем подклассе ячейки переопределите метод setEditing:animated:
следующим образом:
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
// this is an array of the labels / view that you want to animate
NSArray *objectsToMove = @[self.stdDLabel];
// this is the amount of pixel to move - the width of the delete button
float pixelToMove = 70.0f;
float animationDuration = 0.3f;
// calculating the delta. If set editing, move from right to left. otherwise, from left to right
float delta = (editing) ? -pixelToMove : pixelToMove;
// put the move code in a block for avoid repeating code in the if
void (^moveBlock)() = ^{
for (UIView *view in objectsToMove) {
view.center = CGPointMake(view.center.x + delta, view.center.y);
}
};
// we want to move the labels only if editing is different from the current isEditing state
if (editing != self.isEditing)
{
// execute the move block, animated or not
if (animated)
[UIView animateWithDuration:animationDuration animations:moveBlock];
else
moveBlock();
}
// call the super implementation
[super setEditing:editing animated:animated];
}
Ответ 2
Я не проверял весь ваш код, но наверняка вам нужно будет добавлять начальные/конечные обновления с каждой стороны удаления...
[self.drinksTableView beginUpdates];
[self.drinksTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.drinksTableView endUpdates];
... для получения анимации.
Ответ 3
Вы можете выполнить эту задачу, используя gesturerecognizer. Это может помочь вам управлять вашей ячейкой. Также добавьте кнопку удаления custome на ячейку вместо кнопки удаления по умолчанию.
Ответ 4
в tableView:didEndEditingRowAtIndexPath:
отображает задачу переустановки UILabels вручную путем установки их кадров
- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
homeCell *cell = (homeCell *)[tableView cellForRowAtIndexpath:indexPath];
UILabel *labelToBeRelocated = (UILabel *)[cell viewWithTag:YOUR_LABEL_TAG];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.25f];
[labelToBeRelocated setFrame:CGRectMake(New_PosX , New_PosY , width , height)];
[UIView commitAnimations];
}
Так как вышеупомянутый метод делегата вызывается после того, как EditingButton (кнопка Delete) скрыта в UITableViewCell, следовательно, UILabel будет переустанавливать свою позицию только после того, как кнопка удаления будет скрыта.
Надеюсь, это поможет вам.