2012-01-12 57 views
1

我想从UILongPressGestureRecognizer事件的单元格中获取和保存数据。我正在尝试的是,当用户点击并保持很长时间时,将会打开一个对话框(其中将有3个或更多按钮),用户可以选择保存特定的单元格数据,或者从表格中删除该单元格或去另一个屏幕。在UILongPressGestureRecognizer中保存来自tableview单元格的数据

下面是代码我使用这个目的:

-(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]; 
    UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)]; 
    pressRecongnizer.minimumPressDuration = 0.5f; 
    [cell addGestureRecognizer:pressRecongnizer]; 
    [pressRecongnizer release]; 
} 

if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){ 
    cell.textLabel.text = 
    [self.filteredListItems objectAtIndex:indexPath.row]; 
} 
else{ 
    cell.textLabel.text = 
    [self.groups objectAtIndex:indexPath.row]; 
} 

return cell;} 

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

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add to Favourites", @"Take to Map", @"Delete" ,nil] ; 
[alert show];} 

在这里,我想知道我可以将数据保存到我的coreData?

回答

2

UIGestureRecognizer有一个视图属性,它表示它所连接的视图。

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

由于您在每个单元上放置了手势识别器,因此您可以轻松使用上述代码来抓取特定的单元格。

请注意,您必须实施UIAlertDelegate方法并将数据暂时保存在某处,因为用户选择的选项将反映在单独的方法中。

编辑:

由于用户在一个UIAlertView中选择不同的方法给出,你将有一个参考保存到细胞(你是否建立了indexPath,电池等的实例变量..随你便)。

- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer { 
    UITableViewCell *cell = (UITableViewCell *)[recognizer view]; 

    self.myText = cell.textLabel.text; 
    self.currentCellIndexPath = [self.tableView indexPathForCell:cell]; 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add to Favourites", @"Take to Map", @"Delete" ,nil] ; 
    [alert show]; 
} 

要删除单元格,首先需要将其从数据源中删除。现在,您处于您的代表方法中:

if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"Delete"]) { 
    [myArray removeObjectAtIndex:self.currentCellIndexPath]; // in this example, I saved the reference to the cell using a property 

    // last line of example code 
} 

现在您需要使用两种方法之一更新您的表格视图。您可以立即调用刷新表视图:

[self.tableView reloadData]; 

或者,如果你想要漂亮的动画删除意见表中有,你可以使用:

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:self.currentCellIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
+0

感谢名单@Kevin低 – 2012-01-12 08:01:25

+0

但一部分我的问题是剩下的,那就是如何从表格中删除特定的单元格,如果用户点击对话框中的删除按钮 – 2012-01-12 08:07:42

+0

哦,对不起!没有注意到。编辑=)。 – 2012-01-12 08:34:22

相关问题