【问题标题】:Tableview Rows delete iosTableview行删除ios
【发布时间】:2016-12-25 18:25:47
【问题描述】:

我使用了两种(canEditRowAtIndexPath 和 commitEditingStyle)方法根据索引删除行,每当我转到下一个视图并返回表视图时,删除的行都会再次出现。 如何在表格视图中永久删除行?这对我很有帮助。

【问题讨论】:

  • 您需要更新数据源,我的意思是您在 tableView 中显示的对象数组

标签: ios objective-c iphone uitableview


【解决方案1】:

似乎您只是从 UI 中删除了数据,所以您遇到了问题。

您必须同时从源和 UI 中删除数据。

只需参考这段代码:

@interface ViewController ()

@property UITableView* tableView;
@property NSMutableArray* dataArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _dataArray = [[NSMutableArray alloc] init];
    for (int i = 0; i<10; i++) {
        [_dataArray addObject:[NSString stringWithFormat:@"Test%d",i]];
    }

    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];

    _tableView.editing = true;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"MyTableCell"];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyTableCell"];
    }
    cell.textLabel.text = [_dataArray objectAtIndex:indexPath.row];
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return true;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //Delete data from source
        [_dataArray removeObjectAtIndex:indexPath.row];
        //Delete row from UI
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

@end

希望对你有帮助。

【讨论】:

    【解决方案2】:
    1. 使用NSMutableArray 作为您的UITableView's 数据源。
    2. commitEditingStyle 代表....

      - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
             if (editingStyle == UITableViewCellEditingStyleDelete) {
                 [datasourceArray removeObjectAtIndex:indexPath.row];
             }
      }
      

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 1970-01-01
      • 2013-01-02
      • 2017-03-17
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      相关资源
      最近更新 更多