获取与单击按钮对应的表视图控制器中的特定行的数据

时间:2012-09-21 11:00:48

标签: iphone objective-c

我是IOS开发的新手。我正在开发一个应用程序,其中我有几行和每行前面的按钮。在cellForRowAtIndexPath中,我创建了一个名为buttonPressed()的函数,在该函数中我想获取仅与我单击的按钮对应的数据。你能帮我解决这个问题吗?

这就是我在做什么。

   -(void) buttonPressed: (id) sender withEvent: (UIEvent *) event 
   {
       UITouch *touch= [[event allTouched] anyObject];
       CGPoint location = [touch locationInView: self.tableView];
       NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
       trackedUser = [searchResult obectAtIndex:indexPath.row];
   }

trackedUser是一个类的对象,它包含用户的详细信息,例如他的名字,id等。而SearchResult是一个数组,显示表视图控制器中的用户名列表(在搜索栏中搜索)。 / p>

3 个答案:

答案 0 :(得分:0)

//Instead of using Touch Handlers, you can make it more simple!!

cellForRowAtIndexPath数据源中向UIButton添加代码,例如yourButton.tag = indexPath.row;

-(void) buttonPressed: (UIButton *) sender 
{
    NSLog(@"The row %d button was pressed",sender.tag);

    //To get data, simply pass sender.tag as index in your NSArray or WhatEver you're using for storing data.
}

答案 1 :(得分:0)

创建按钮时,将标签设置为按钮。

btn.tag= indexPath.row;

按下按钮后,访问带标签值

的按钮
-(void) buttonPressed: (UIButton *) sender 
{
    UIButton *btn = (UIButton*)sender;
    switch (btn.tag) {
        case 0:
            //Thing you want to perform
            break;

        default:
            break;
    }
}

答案 2 :(得分:0)

cellForRowAtIndexPath-Adding按钮修改为单元格代码,如下所示

UIButton *yourButton = [[UIButton alloc] initWithtarget:..] //creating UIButton with frame and target method
yourButton.tag= indexPath.row;
[cell addSubview:yourButton];
[yourButton release];

然后修改 buttonPressed 方法,如下所示

-(void) buttonPressed: (id) sender withEvent: (UIEvent *) event 
{
       UIButton *myBtn = (UIButton *)sender;
       trackedUser = [searchResult obectAtIndex:myBtn.tag];
}