6

カスタム TableCell があり、UiButton が IB を介してこれに関連付けられています。ただし、ボタン アクション メソッドは常にボタン インデックスをゼロとして返します。

以下は私のコードです

//Inside CellForRow
[cell.M_CtrlBtnChat addTarget: self
                       action: @selector(buttonPressed:withEvent:)
             forControlEvents: UIControlEventTouchUpInside];


- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{

    UITouch * touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView: self.tableView];
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];
    NSLog(@"%d", indexPath.row);
}

ここで、インデックス パスは常にゼロを返します。何か案が 。私を助けてください

4

4 に答える 4

2

私は同じ問題を抱えていて、すべてを試しました。最終的にそれを行ったのは、メソッドを実装することでした

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

カスタムセルの高さを返すだけです(NIBファイルを見てください)

于 2013-09-07T22:43:01.407 に答える
0

この以下のコードを使用して試してみてください..

- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *)button.superview;
    UITableView *tableView = (UITableView *)cell.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSLog(@"%d", indexPath.row);
}

また

UIButton *button = (UIButton *)sender;
CGRect buttonFrame = [button convertRect:button.bounds toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonFrame.origin];

または プログラムでセルにカスタムボタンを追加した例全体

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
         .......
    cell.textLabel.text = [NSString stringWithFormat:@"Cell #%i", indexPath.row + 1];

    //Create the button and add it to the cell
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(customActionPressed:)
     forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Custom Action" forState:UIControlStateNormal];
    button.frame = CGRectMake(150.0f, 5.0f, 150.0f, 30.0f);
    [cell addSubview:button];

    return cell;
}

次のコードでインデックスパスを取得します...

//Get the superview from this button which will be our cell
UITableViewCell *tblCell = (UITableViewCell*)[sender superview];

//From the cell get its index path.
NSIndexPath *indexPathE = [myTableView indexPathForCell:tblCell];
NSLog(@"%d", indexPathE.row);
于 2013-07-22T11:45:48.190 に答える