按下BarButtonItem后,在每个单元格中使用按钮更新TableView

时间:2011-11-07 14:51:31

标签: iphone uibutton uitableview

我有一个带有uinavigation栏的tableviewcontroller,它有一个barbuttonitem,名为editBarButton。当按下editBarButton时,我希望我的tableview更新为每个单元格中的一个新按钮,表示“编辑”。实现这个的正确方法是什么?

- (void)onEditBarButtonPressed{
    //TODO: update cells
}

2 个答案:

答案 0 :(得分:0)

您必须使用“修改”按钮覆盖accessoryView中的UITableViewCell属性:

创建一个自定义按钮以覆盖当前的accesoryView:

- (UIButton *) makeDetailDisclosureButton
{
    UIButton * button = [UIButton yourEditButton];

[button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];

    return ( button );
}

然后按钮将在完成后调用此例程,然后为附件按钮提供标准的UITableViewDelegate例程:

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;

    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}

您可以在此处看到类似的问题:Using a custom image for a UITableViewCell's accessoryView and having it respond to UITableViewDelegate

答案 1 :(得分:0)

我找到了解决问题的方法。

您应该添加一个名为editPressed的对象级BOOL标志。 它应该在viewDidLoad中设置为NO。

制作每个单元格时,为每个单元格添加一个按钮,如果需要,将其设置为隐藏:

[button setHidden:!editPressed];

使用该标志非常重要,这样当新单元格生成时,如果它们应该是或者可见,则它们将保持隐藏按钮。

然后在视图控制器中有一个对象级别NSMutableArray *并添加每个按钮:

[buttons addObject:button];

当您想要显示每个按钮时,只需更改隐藏状态:

editPressed = YES;
for(int i = 0; i != [butttons count]; i++){
    [[buttons objectAtIndex:i] setHidden:!editPressed];
}

如果要隐藏每个按钮,请再次更改隐藏状态:

editPressed = NO;
for(int i = 0; i != [butttons count]; i++){
    [[buttons objectAtIndex:i] setHidden:!editPressed];
}