从自定义原型单元格中以编程方式选择“表视图”行

时间:2014-02-24 17:33:34

标签: ios uitableview segue

我有一个PrototypeCell,里面有两个按钮,每个按钮都会切换到显示项目的另一个详细视图。当我触摸单元格中的按钮时,我将NSNumber设置为所选按钮索引(1或2)并设置所选单元格。然后单元格将其颜色更改为灰色(突出显示),但UITableViews委托方法didSelectRowAtIndexPath不会被调用。

我该怎么做正确的方法?无法弄明白。

到目前为止,这是我的代码:

UITableViewController内部

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    TwoButtonPrototypeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell setupButtons];
    NSArray *array1 = [entries objectAtIndex:indexPath.row * 2];
    NSArray *array2 = [entries objectAtIndex:indexPath.row * 2 + 1];
    cell.identifier1 = [array1 objectAtIndex:0];
    cell.identifier2 = [array2 objectAtIndex:0];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TwoButtonPrototypeCell *cell = (TwoButtonPrototypeCell *)[tableView cellForRowAtIndexPath:indexPath];
    identifier = cell.touchedButtonIdentifier;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self performSegueWithIdentifier:@"showDetails" sender:self];
}

在TwoButtonPrototypeCell内部

- (void)setupButtons {
    [button1 addTarget:self action:@selector(touchedButton1) forControlEvents:UIControlEventTouchUpInside];
    [button2 addTarget:self action:@selector(touchedButton2) forControlEvents:UIControlEventTouchUpInside];
}

- (void)touchedButton1 {
    touchedButtonIdentifier = identifier1;
    [self setSelected:YES animated:NO];
}

- (void)touchedButton2 {
    touchedButtonIdentifier = identifier2;
    [self setSelected:YES animated:NO];
}

1 个答案:

答案 0 :(得分:1)

在您的单元格中实施协议,然后在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中 设置代理

cell.delegate = self;

按下按钮时调用cells delegate方法,例如你在tableViewController中实现了这个协议方法

    - (void)cellButtonWasPressed:(TwoButtonPrototypeCell*)cell {
        [self tableView:self.tableView didSelectRowAtIndexPath:[self.tableView indexPathForCell:cell]];    

}

所以基本上在你的单元格中你这样做:

- (void)touchedButton1 {
    touchedButtonIdentifier = identifier1;
    [self.delegate cellButtonWasPressed:self];
}