iOS,如何查找UITableView的选定行?

Pra*_*ria 28 iphone objective-c uitableview ios

我试图找到UITableViewCell如下选择:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 

       reuseIdentifier:CellIdentifier];

  }
    if   ([indexPath row] == [tableView cellForRowAtIndexPath:indexPath.row]) // i want to place value of selected row to populate the buttons 

        //([indexPath row] == 0)

        //(indexPath.row == ![self cellIsSelected:indexPath]) 

    {
        UIButton *AddComment = [UIButton buttonWithType:UIButtonTypeCustom]; // custom means transparent it takes shape same with backgroup image

        [AddComment addTarget:self 
                       action:@selector(TestBtns:)
             forControlEvents:UIControlEventTouchDown];

        // [AddComment setTitle:@"1" forState:UIControlStateNormal];

        AddComment.frame = CGRectMake(9.0, 128.0, 96.0, 26.0);

        [cell.contentView addSubview:AddComment];

        UIImage *buttonAddComment = [UIImage imageNamed:@"addcomment.png"];

        [AddComment setBackgroundImage:buttonAddComment forState:UIControlStateNormal];

        [cell.contentView addSubview:AddComment]; 


    }
Run Code Online (Sandbox Code Playgroud)

如何实现这一点,请你指导我,我在做错误的地方.

Sur*_*mas 105

NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
Run Code Online (Sandbox Code Playgroud)

  • 为什么不接受这个作为正确答案?@pratap Manish Bhadoria (5认同)

iPa*_*tel 16

使用此委托方法UITableView

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@"%d", indexPath.row); // you can see selected row number in your console;
}
Run Code Online (Sandbox Code Playgroud)


Vai*_*tam 6

在UITableViewDataSource委托中有一个方法- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath.

它返回NSIndexPath对象,该对象包含选定的部分和选定的行.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"Selected section>> %d",indexPath.section);
    NSLog(@"Selected row of section >> %d",indexPath.row);
}
Run Code Online (Sandbox Code Playgroud)

确保在使用之前设置tableview的数据源,否则不会调用此方法