1

我是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 是一个数组,它在表格视图控制器中显示用户名列表(在搜索栏中搜索时)。

4

3 回答 3

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.
}
于 2012-09-21T11:10:50.870 回答
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];
}
于 2012-09-21T11:57:45.980 回答
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;
    }
}
于 2012-09-21T11:46:19.237 回答