Действия для UIButtons в UITableViewCells - PullRequest
0 голосов
/ 03 ноября 2011

Я реализовал UIButton в каждой ячейке моего UITableView и установил действие для этой кнопки.Теперь я пытаюсь выяснить, какая из этих кнопок была нажата:

- (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] autorelease];
    }

    // Configure the cell...
    <...>

    UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    but.frame= CGRectMake(275, 5, 40, cell.frame.size.height-10);
    [but setTitle:@"Map" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(Map:) forControlEvents:UIControlEventTouchUpInside];

    [cell.contentView addSubview:but];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;

}

- (IBAction) Map: (id) sender {
    NSIndexPath *indexPath = [[NSIndexPath alloc] init];
    indexPath = [tableView indexPathForCell:(UITableViewCell*)[[sender superview]superview]];
    [delegate callMap: [[[data objectAtIndex:indexPath.section] 
                         objectAtIndex:indexPath.row+1] 
                        objectAtIndex:kNameInArray]

                     : [[[[data objectAtIndex:indexPath.section] 
                          objectAtIndex:indexPath.row+1] 
                         objectAtIndex:kXcoordinateInArray] doubleValue]

                     : [[[[data objectAtIndex:indexPath.section] 
                          objectAtIndex:indexPath.row+1] 
                         objectAtIndex:kYcoordinateInArray] doubleValue]
     ];
}

Но он всегда отправляет data[0][1][*] элементы делегату.Я имею в виду indexPath всегда имеет 0 необработанных и 0 разделов.Где моя ошибка?

1 Ответ

2 голосов
/ 03 ноября 2011

Сделайте следующее: добавьте кнопку в ваш метод if (cell == nil) { ... }, иначе у вас будет много кнопок внутри одной и той же ячейки, когда ваша ячейка будет использоваться повторно.
Установите cell.contentViow.tag = SomeValueIdentifyingYourData (некоторое значение типа int, представляющее вашу модель .. может быть, просто индекс массива вашего объекта ..) перед возвратом ячейки.
Внутри вашего Map: метода вы можете снова получить доступ к значению с помощью ((UIButton)sender).superview.tag и принимать решения на основе этого значения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...