在UITableView的编辑模式下获取indexPath

时间:2014-01-03 22:02:49

标签: ios iphone uitableview custom-cell

我有一个带自定义单元格的UITableView。每当UITableView处于编辑模式时,我在自定义单元格中都有以下代码。

- (void)willTransitionToState:(UITableViewCellStateMask)state{

    [super willTransitionToState:state];

    if (state == UITableViewCellStateShowingEditControlMask)
    {
        self.delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.delBtn setFrame:CGRectMake(10, 15, 25, 25)];
        [self.delBtn setImage:[UIImage imageNamed:@"noSelection.png"] forState:UIControlStateNormal];
        buttonCurrentStatus = YES;
        [self.delBtn addTarget:self action:@selector(delBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.delBtn];
    }
    else
    {
        if(self.delBtn)
        {
            [self.delBtn removeFromSuperview];
            self.delBtn = nil;
        }
    } }

- (void)delBtnPressed:(id)sender {
    if (buttonCurrentStatus == NO)
    {
        buttonCurrentStatus = YES;
        [self.delBtn setImage:[UIImage imageNamed:@"noSelection.png"] forState:UIControlStateNormal];
    }
    else
    {
        buttonCurrentStatus = NO;
        [self.delBtn setImage:[UIImage imageNamed:@"selection.png"] forState:UIControlStateNormal];
    } }

现在如何从UITableview的CustomCell获取indexPath?

2 个答案:

答案 0 :(得分:0)

您可以使用UITableView indexPathForCell:

显然,为此您需要引用单元格类中的表。如果您想使其成为您单元格的属性,请务必将其设为weak以避免参考周期。

答案 1 :(得分:0)

我发现这样做的最好方法是在单元格上创建委托/协议。使委托成为ViewController并将其传入。然后,您可以在tableview上调用indexPathForCell。示例如下。

- (void)willTransitionToState:(UITableViewCellStateMask)state{

    [super willTransitionToState:state];

    if (state == UITableViewCellStateShowingEditControlMask)
    {
        self.delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.delBtn setFrame:CGRectMake(10, 15, 25, 25)];
        [self.delBtn setImage:[UIImage imageNamed:@"noSelection.png"] forState:UIControlStateNormal];
        buttonCurrentStatus = YES;
        [self.delBtn addTarget:self action:@selector(delBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.delBtn];
    }
    else
    {
        if(self.delBtn)
        {
            [self.delBtn removeFromSuperview];
            self.delBtn = nil;
        }
    } }

- (void)delBtnPressed:(id)sender {
    if (buttonCurrentStatus == NO)
    {
        buttonCurrentStatus = YES;
        [self.delBtn setImage:[UIImage imageNamed:@"noSelection.png"] forState:UIControlStateNormal];
    }
    else
    {
        buttonCurrentStatus = NO;
        [self.delBtn setImage:[UIImage imageNamed:@"selection.png"] forState:UIControlStateNormal];
    }

    if ([self.delegate respondsToSelector:(customCelldelBtnPressed:)]) {
        [self.delegate customCelldelBtnPressed:self];
    }
}

//当然,您需要实际创建委托或协议并在视图控制器上实现它。