无法在UITableView中获得插入控件

时间:2010-06-19 22:36:23

标签: iphone uitableview

我在网上搜索过,我的代码似乎几乎与所有内容相同,但是我无法让我的UITableView编辑工作以插入行。当我单击编辑按钮时,我现有的所有行都会获得删除控件,但我没有额外的行进行插入。我把头发拉出来似乎应该是一件简单的事情。我错过了什么?

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [categoryTV setEditing: editing animated:animated];

    NSIndexPath *ip = [NSIndexPath indexPathForRow:[[appDelegate appCategories] count] inSection:0];

    [self.categoryTV beginUpdates];
        if (editing) {
            [categoryTV insertRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationLeft];
        } else {
            [categoryTV deleteRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationFade];          
        }
    [self.categoryTV endUpdates];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 ...

    if (indexPath.row >= [[appDelegate appCategories] count])
        cell.textLabel.text = NSLocalizedString(@"New Category", @"NewCategoryCellText");
    else
        cell.textLabel.text = [[[appDelegate appCategories] objectAtIndex:indexPath.row] detailValue];


    ....

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.editing) {
        return [[appDelegate appCategories] count] + 1;
    } else {
        return [[appDelegate appCategories] count];
    }
}

如上所述,我忘了包含我建议的方法版本,现在如下所示。感谢。

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [[appDelegate appCategories] count]) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}

3 个答案:

答案 0 :(得分:3)

您需要实现以下委托方法来指定编辑样式:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleInsert;
}

显然,您只会为要插入控件的单元格返回该值。否则,您需要返回UITableViewCellEditingStyleDelete

答案 1 :(得分:1)

我在UITableView中看到了类似的行为,问题是我的canEditRowAtIndexPath方法为插入控件行返回了NO

答案 2 :(得分:1)

设置tableview编辑属性YES

- (void)viewDidLoad {
    .......
    self.tableView.editing = YES;   //set editing property of tableview
    .......
}
  

编辑 - 一个布尔值,用于确定表格视图是否处于编辑模式。

     

<强>声明

     

@property(非原子,getter = isEditing)BOOL编辑

     

<强>讨论

     

当此属性的值为YES时,表视图正在编辑中   mode:表格的单元格可能显示插入或删除   每个细胞左侧的控制和对细胞的重新排序控制   右侧,取决于单元格的配置方式。 (看到   UITableViewCell类参考有关详细信息。)点击控件会导致   用于调用数据源方法的表视图   tableView:commitEditingStyle:forRowAtIndexPath:.   默认值为NO。

然后返回您想要插入控件的单元格

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleInsert;
}