2012-01-20 4 views
0

Я использовал пользовательскую ячейку в своем представлении таблицы для разных значений и для сохранения значения в основных данных. Я использовал UILongPressGestureRecognizer, так что, когда пользователь нажимает на ячейку надолго, откроется диалоговое окно, дающее пользователю возможность добавить значение этой конкретной ячейки в основные данные.Значение ячейки таблицы для основных данных

Мой код для этого:

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

    NSString * cellValue; 
    if (tableView == listTable) 
    { 
     cellValue = [listVehicles objectAtIndex:indexPath.row]; 
    } 
    else // handle search results table view 
    { 
     cellValue = [filteredListItems objectAtIndex:indexPath.row]; 
    } 

    static NSString *CellIdentifier = @"vlCell"; 

    VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) 
    { 
     NSLog(@"Cell Created"); 

     NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"VehicleListCell" owner:nil options:nil]; 

     for (id currentObject in nibObjects) { 
      if ([currentObject isKindOfClass:[VehicleListCell class]]) { 
       cell = (VehicleListCell *)currentObject; 
      } 
     } 

     UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)]; 
     pressRecongnizer.minimumPressDuration = 0.5f; 
     [cell addGestureRecognizer:pressRecongnizer]; 
     [pressRecongnizer release]; 
    } 

    cell.textLabel.font = [UIFont systemFontOfSize:10]; 

    [[cell ignition] setImage:[UIImage imageNamed:@"ignition.png"]]; 
    [[cell direction] setImage:[UIImage imageNamed:@"south.png"]]; 

    cell.licPlate.text = cellValue; 

    return cell; 
} 

для longpressgesture:

- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer { 

    UITableViewCell *cell = (UITableViewCell *) [recognizer view]; 
    NSString *text = cell.textLabel.text; 

    NSLog(@"cell value: %@", text); 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil] ; 

    [alert addButtonWithTitle:@"Add to Favourites"]; 
    [alert addButtonWithTitle:@"Take to Map"]; 

    [alert show]; 
} 


-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex { 

    NSString *title = [alert buttonTitleAtIndex:buttonIndex]; 

    if([title isEqualToString:@"Add to Favourites"]) 
    { 
     NSLog(@"Added to favourites."); 
    } 
    else if([title isEqualToString:@"Take to Map"]) 
    { 
     NSLog(@"Go to MapView"); 
    } 
} 

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

Как я могу получить значение каждой ячейки, нажав на нее, а затем сохраните ее на основные данные?

Редакция:

Я создал контроллер представления с XIb файлом для пользовательской ячейки:

его .h файла как:

@interface VehicleListCell : UITableViewCell{ 

IBOutlet UILabel *licPlate; 
IBOutlet UILabel *commDate; 

IBOutlet UIImageView *ignition; 
IBOutlet UIImageView *direction; 

IBOutlet UITableViewCell *cell; 
} 

@property (nonatomic, strong) IBOutlet UILabel *licPlate; 
@property (nonatomic, strong) IBOutlet UILabel *commDate; 
@property (nonatomic, strong) IBOutlet UIImageView *ignition; 
@property (nonatomic, strong) IBOutlet UIImageView *direction; 

@end 

ответ

0

Я не уверен, как вам настроить ваш VehicleListCell, но он может иметь другое свойство, чем обычное UITableView, поэтому измените свой

UITableViewCell *cell = (UITableViewCell *) [recognizer view]; 

в

- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer 

в

VehicleListCell* cell = (VehicleListCell *)[recognizer view]; 

редактировать

попробовать этот код

- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer { 

    VehicleListCell* cell = (VehicleListCell *)[recognizer view]; 
    NSString *text = cell.licPlate.text; 

    NSLog(@"cell value: %@", text); 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil] ; 

    [alert addButtonWithTitle:@"Add to Favourites"]; 
    [alert addButtonWithTitle:@"Take to Map"]; 

    [alert show]; 
} 
+0

Thanx X Slash, я редактировал свой вопрос, пожалуйста, проверьте –

+0

я попробовал то, что у вас есть предложил, и его сделали :) Но у меня есть еще один вопрос, связанный с этим ... мое диалоговое окно не увольняется на один клик, я должен нажать (либо кнопку) 3 раза, тогда диалоговое окно исчезнет. Что может быть проблемой за этим? –

+0

Ваш NSLog печатает несколько раз? (Это одно значение NSLog (значение «@»:% @ », текст);) если этот файл печатается несколько раз, это может быть потому, что ваш распознаватель жестов обнаруживает более одного входа –

Смежные вопросы