2012-01-12 62 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