Прокрутка для удаления таблицы TableView
У меня есть массив:
self.colorNames = [[NSArray alloc]
initWithObjects:@"Red", @"Green",
@"Blue", @"Indigo", @"Violet", nil];
Я пробовал все, что могу найти, но всегда есть ошибки. Я хочу иметь возможность прокручивать так, чтобы появилась кнопка удаления, а затем нажмите кнопку удаления и удалите эту строку.
Полный код (все, что относится к таблице):
// HEADER FILE
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *tableView;
NSMutableArray *colorNames;
}
@property (strong, nonatomic) NSArray *colorNames;
@end
// IMPLEMENTATION
#import "ViewController.h"
@implementation ViewController
@synthesize colorNames;
- (void)viewDidLoad {
[super viewDidLoad];
self.colorNames = [[NSMutableArray alloc]
initWithObjects:@"Red", @"Green",
@"Blue", @"Indigo", @"Violet", nil];
[super viewDidLoad];
//[tableView setEditing:YES animated:NO];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int count = [colorNames count];
return count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell.
cell.textLabel.text = [self.colorNames objectAtIndex: [indexPath row]];
return cell;
}
Ответы
Ответ 1
Вам необходимо реализовать необходимые методы UITableViewDelegate
и UITableViewDataSource
.
Сначала добавьте следующее:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
Тогда:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//remove the deleted object from your data source.
//If your data source is an NSMutableArray, do this
[self.dataArray removeObjectAtIndex:indexPath.row];
[tableView reloadData]; // tell table to refresh now
}
}
Ответ 2
Для начала ваш colorNames
должен быть NSMutableArray, а не NSArray. Вы не можете добавлять или удалять объекты из обычного (не изменяемого) массива; вы должны воссоздавать его каждый раз, когда вы вносили изменения. Переключение, которое сделает это проще. Для вашей реализации -tableView:commitEditingStyle:forRowAtIndexPath:
, вы сможете сделать что-то вроде этого:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle == UITableViewCellEditingStyleDelete)
{
[colorNames removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
Ответ 3
Выполните следующий метод:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
Ответ 4
Swift 3 и Swift 4 без использования reloadDatastrong >
Я предпочитаю использовать deleteRows вместо использования reloadData.
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Enables editing only for the selected table view, if you have multiple table views
return tableView == yourTableView
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Deleting new item in the table
yourTableView.beginUpdates()
yourDataArray.remove(at: indexPath.row)
yourTableView.deleteRows(at: [indexPath], with: .automatic)
yourTableView.endUpdates()
}
}
Ответ 5
Это то, что сработало для меня
-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete){
Comment *comment = [self.commentArray objectAtIndex:indexPath.row];
dispatch_async(kBgQueue, ^{
if([self.thePost deleteCommentForCommentId:comment.commentId]){
if (indexPath.row < self.commentArray.count) {
[self.commentArray removeObjectAtIndex:indexPath.row];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tvComments reloadData];
});
}
});
}
[self.tvComments reloadData];
}
Ответ 6
Быстрая версия:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
dataArray?.removeAtIndex(indexPath.row)
tableview.reloadData()
}
}
Ответ 7
Версия Swift 4:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in
// delete item at indexPath
}
return [delete]
}