滑动即可删除或。 iPhone上的编辑按钮

时间:2010-09-05 18:01:59

标签: iphone uitableview

我将viewController设置为以Apple推荐的方式使用编辑按钮:

self.navigationItem.rightBarButtonItem = self.editButtonItem;

当用户点击编辑按钮时,会导致setEditing:animated:方法触发。在此方法中,我根据editing值添加或删除“新行”(即用户可以点按以添加新项目的行)。

当用户在单元格中滑动(不处于编辑模式)时,它也会调用setEditing:animated:,这会导致我的代码错误地添加此“新行”。它应该只在整个viewController处于编辑模式时(即点击编辑按钮时)显示这个新行。

如何解决此问题?

5 个答案:

答案 0 :(得分:11)

如果您实施tableView:willBeginEditingRowAtIndexPath:tableView:didEndEditingRowAtIndexPath:,方法调用的行为将会改变......

它将不再调用setEditing:animated:,您必须处理上述两种方法中的所有编辑更改逻辑。作为此的副作用,当调用滑动手势时,self.editing将不再是YES。这是因为setEditing:animated:负责设置self.editing = YES

答案 1 :(得分:3)

使用UITableViewDelegate方法tableView:willBeginEditingRowAtIndexPath:。来自文档:

"This method is called when the user swipes horizontally across a row; as a 
consequence, the table view sets its editing property to YES (thereby entering editing 
mode) and displays a Delete button in the row identified by indexPath. In this "swipe to 
delete" mode the table view does not display any insertion, deletion, and reordering 
controls. This method gives the delegate an opportunity to adjust the application's user 
interface to editing mode. When the table exits editing mode (for example, the user taps 
the Delete button), the table view calls tableView:didEndEditingRowAtIndexPath:."

tableView:willBeginEditingRowAtIndexPath:中,设置一个标记,即使用滑动删除来触发编辑模式。然后,在setEditing:animated:中,检查标志以查看是否正常触发编辑模式,或使用滑动删除并根据该检查执行某些操作。最后,重置tableView:didEndEditingRowAtIndexPath:中的标志,以便在按下编辑按钮时执行默认操作。

答案 2 :(得分:0)

我不知道你的“新行”是什么,但你可以将你的编辑按钮附加到一个帮助方法,该方法在调用setEditing之前设置一个标志,你可以检查所述标志是否已设置并相应地表现。然后清除方法末尾的标志。

答案 3 :(得分:0)

有意义的你必须覆盖setEditing:animated:方法。或者甚至你可以像Eiko建议的那样在这种方法中设置旗帜。

或其他方式

你实现自定义导航栏。在这种情况下,你需要导航栏的图像和它上面的2个按钮。 将目标添加到该按钮并根据需要实现功能

答案 4 :(得分:0)

当用户点击“编辑”按钮以及在单元格上滑动时,表格都进入编辑模式。要区分这两种情况,您可以覆盖willBeginEditingRowAtIndexPath(记住不要调用超级或进入编辑模式)并将索引路径存储在属性中。覆盖setEditing,您可以检查属性,并且仅在插入行为nil时(即,当用户不刷卡时)添加行。

@interface MasterViewController ()

@property (nonatomic, strong, nullable) NSIndexPath *tableViewEditingRowIndexPath;

@end

@implementation MasterViewController

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tableViewEditingRowIndexPath = indexPath;
    [super tableView:tableView willBeginEditingRowAtIndexPath:indexPath]; // calls setEditing:YES
}

-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    [super tableView:tableView didEndEditingRowAtIndexPath:indexPath]; // calls setEditing:NO
    self.tableViewEditingRowIndexPath = nil;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if(self.tableViewEditingRowIndexPath){
         // we are swiping
         return;
    }
    if(editing){
        // insert row for adding
    }
    else{
        // remove row for adding
    }
}