Как включить прокрутку для удаления ячейки в TableView?
У меня есть UIViewController
, который реализует протоколы делегатов TableViews и datasource.
Теперь я хочу добавить "салфетки для удаления" жестов в ячейки.
Как мне это сделать.
Я дал пустую реализацию метода commitEditingStyle
, а также установил для свойства "Редактирование" значение "ДА".
Тем не менее функция салфетки не подходит.
Теперь мне нужно отдельно добавить UISwipeGesture
в каждую ячейку?
Или я что-то не хватает?
Ответы
Ответ 1
Вам не нужно устанавливать editing:YES
, если вам нужно отобразить кнопку "Удалить" при прокрутке ячейки. Вы должны реализовать tableView:canEditRowAtIndexPath:
и вернуть там оттуда строки, которые нужно отредактировать/удалить. Это необязательно, если ваш tableView dataSource является подклассом UITableViewContoller - этот метод, если он не переопределен, возвращает YES по умолчанию. Во всех остальных случаях вы должны его реализовать.
EDIT:. Вместе мы обнаружили проблему - tableView:editingStyleForRowAtIndexPath:
возвратили UITableViewCellEditingStyleNone
, если таблица не была в режиме редактирования.
Ответ 2
Как уже отмечалось Dan, вам необходимо реализовать следующие методы делегирования представления таблиц:
-
tableView:canEditRowAtIndexPath:
-
tableView:commitEditingStyle:forRowAtIndexPath:
Примечание. Я пробовал это в iOS 6 и iOS 7.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return YES - we will be able to delete all rows
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Perform the real delete action here. Note: you may need to check editing style
// if you do not perform delete only.
NSLog(@"Deleted row.");
}
Ответ 3
// 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 YES;
}
// 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:@[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
}
}
Ответ 4
Пожалуйста, попробуйте этот код быстро,
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// let the controller to know that able to edit tableView row
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
// add the action button you want to show when swiping on tableView cell , in this case add the delete button.
let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in
// Your delete code here.....
.........
.........
})
// You can set its properties like normal button
deleteAction.backgroundColor = UIColor.redColor()
return [deleteAction]
}
Ответ 5
Попробуйте добавить в свой класс следующее:
// Override to support conditional editing of the table view.
- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return(YES);
}
Ответ 6
Заключение Кир Dunenkoff чат
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
}
не следует определять, если вам нужна кнопка удаления, чтобы отображаться при прокрутке.
Ответ 7
Это была проблема для меня тоже... Я мог только прокручивать, чтобы удалить, чтобы работать каждые 10 или около того попыток. Оказывается, gesture
на телевизоре блокируется другим жестом в контроллере родительского представления. Телевизор был вложен в MMDrawerController
(макет ящика с макияжем).
Просто настроить распознаватель жестов в контроллере выдвижного ящика, чтобы не реагировать на тесные жесты во фланговых ящиках, разрешенных для удаления, чтобы работать на моем телевизоре.
Вы также можете попробовать сделать что-то подобное с помощью gesture delegate
:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
Ответ 8
Это быстрая версия
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
Ответ 9
Если вы используете NSFetchedResultsControllerDelegate
для заполнения вида таблицы, это сработало для меня:
- Убедитесь, что
tableView:canEditRowAtIndexPath
всегда возвращает true
-
В вашей реализации tableView:commitEditingStyle:forRowAtIndexPath
не удаляйте строку непосредственно из представления таблицы. Вместо этого удалите его с помощью контекста управляемого объекта, например:
if editingStyle == UITableViewCellEditingStyle.Delete {
let word = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Word
self.managedObjectContext.deleteObject(word)
self.saveManagedObjectContext()
}
func saveManagedObjectContext() {
do {
try self.managedObjectContext.save()
} catch {
let saveError = error as NSError
print("\(saveError), \(saveError.userInfo)")
}
}
Ответ 10
По моему опыту, похоже, что у вас должно быть editing
на UITableView
, установленном на NO
для прокрутки для работы.
self.tableView.editing = NO;
Ответ 11
После iOS 8.0 вы можете настроить свое действие в
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
Ответ 12
NSMutableArray *post= [NSMutableArray alloc]initWithObject:@"1",@"2",@"3",nil];
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSUInteger count = [posts count];
if (row < count) {
return UITableViewCellEditingStyleDelete;
} else {
return UITableViewCellEditingStyleNone;
}
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSUInteger count = [posts count];
if (row < count) {
[posts removeObjectAtIndex:row];
}
}
Ответ 13
Вы можете увидеть все необходимые методы, создав в XCode 5 класс UITableViewController (временный), а затем скопируйте тот метод, который вы хотели бы использовать. Те методы, которые вам нужны, будут закомментированы с заранее заполненными строками, которые вы хотите.