Пользовательская кнопка удаления в ячейке uitableview не работает - PullRequest
0 голосов
/ 07 октября 2011

Я создал tableView с массивом FilterReservations , который содержит объекты Rezervacija.Я добавил пользовательскую кнопку «доска», и когда кнопка нажата, я запрашиваю в виде предупреждения подтверждение этого и затем отправляю запрос на сервер.При получении ответа сервера мне нужно удалить строку из таблицы и объект из массива FilterReservations.Когда я удаляю первую строку, все нормально, но после этого в фильтре ReRezVacija вместо объекта Rezervacija я получил объекты UIButton!Я не знаю, КАК:)

Код:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return([filteredReservations count]);
}

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

    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    }
    Reservation *reservation = [filteredReservations objectAtIndex:indexPath.row];
    NSString *label = [[NSString alloc] initWithFormat:@"%@ (%d)", reservation.name, reservation.seatsNumber];
    cell.textLabel.text = label;
    [label release];
    [reservation release];
    tableView.allowsSelection = FALSE;
    UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [cellButton setFrame:CGRectMake(430.0, 2.0, 106.0, 40.0)];
    [cellButton setTitle:@"Board" forState:UIControlStateNormal];
    [cellButton addTarget:self action:@selector(BoardPassengers:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:cellButton];
        cellButton.tag = indexPath.row;

    return cell;
}


-(void)BoardPassengers:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Question" message:@"Do you want to board passengers?"
                                                   delegate:self cancelButtonTitle:@"Odustani" otherButtonTitles:@"Da", nil];
    [alert show];
    [alert release];
    passengerForBoarding = [NSIndexPath indexPathForRow:((UIControl*)sender).tag inSection:1];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0)
    {
        NSLog(@"cancel");
    }
    else
    {
        Reservation *reservationNew = [filteredReservations objectAtIndex:passengerForBoarding.row];
        NSString *reservationId = [[NSString alloc] initWithFormat:@"%d",reservationNew.reservationId];

        params = [NSDictionary dictionaryWithObjectsAndKeys: @"1", @"tour_id", @"1", @"bus_number",reservationId, @"reservation_id", nil];  
        [[RKClient sharedClient] post:@"/service/boardingToBus.json" params:params delegate:self];
        [DSBezelActivityView newActivityViewForView:self.view withLabel:@"Boarding..."];
    }
}

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {  

    if([[request resourcePath] isEqualToString:@"/service/boardingToBus.json"]){
        if([[response bodyAsString] isEqualToString:@"ERROR"]){
            [DSBezelActivityView removeViewAnimated:YES];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error." 
                                                           delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
        }else{
            [DSBezelActivityView removeViewAnimated:YES];

            [filteredReservations removeObjectAtIndex:passengerForBoarding.row];
            [self.tableView reloadData];

            //[self.tableView beginUpdates];
            //[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:passengerForBoarding]
            //                 withRowAnimation:UITableViewRowAnimationFade];
           // NSLog(@"%i", passengerForBoarding.row);

            //[self.tableView endUpdates];

        }
    }

} 

Ответы [ 2 ]

1 голос
/ 07 октября 2011

Похоже, вам нужно убедиться, что табличное представление явно знает, сколько отфильтрованных резервирований ему нужно отобразить.

// assuming only one section for your table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return([filteredReservations count]);
}

Для получения дополнительной информации:

http://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/tableView:numberOfRowsInSection:

0 голосов
/ 07 июня 2012

Эй, вы можете получить значение «Reservation ID».

-(void)BoardPassengers:(id)sender{
    Reservation *reservationNew = [filteredReservations objectAtIndex:[sender tag]];
    NSString *reservationId = [NSString StringWithFormat:@"%d",reservationNew.reservationId];}

Или вы можете использовать это значение в любом месте, как вы упомянули через окно оповещения.

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