滑动以删除TableView行 [英] Swipe To Delete TableView Row

查看:117
本文介绍了滑动以删除TableView行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的数组:

self.colorNames = [[NSArray alloc] 
initWithObjects:@"Red", @"Green",
@"Blue", @"Indigo", @"Violet", nil];

我尝试了一切我可以找到,但总是有错误。我想要能够滑动,以便显示删除按钮,然后按删除按钮并删除该行。

I've tried everything I can find, but there's always errors. I want to be able to swipe so that the delete button appears, and then press the delete button and have that row removed.

完整代码(与表格相关的一切) :

Full code (everything relating to the table):

// 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;

 }


推荐答案

ve实现必要的 UITableViewDelegate UITableViewDataSource 方法。

You've to implement the necessary UITableViewDelegate and UITableViewDataSource methods.

首先,添加:

- (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
    }
}

这篇关于滑动以删除TableView行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆