2010-10-27 51 views
95

我想有選擇索引UITableView。 我已經寫了下面的代碼:獲取所選的索引的UITableView

NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:0]; 
[tableView scrollToRowAtIndexPath:index 
       atScrollPosition:UITableViewScrollPositionTop 
         animated:YES]; 

這總是第一個項目工作。我想在indexPathForRow.

請幫忙。 謝謝。

回答

201
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow]; 
+5

如果您允許多個選擇,請考慮使用: - (NSArray *)indexPathsForSelectedRows – yura 2015-02-19 19:12:32

+2

不再有效 – 2015-03-05 06:02:33

+0

@Codecracker我測試了代碼。它仍然有效。 – yuchaozh 2016-05-23 21:16:51

4

在didSelectRowAtIndexPath中,將聲明NSIndexPath的接口設置爲返回的索引路徑。然後你可以滾動到那個變量。如果你需要幫助,評論和我可以給一些示例代碼。

+0

是請張貼一些示例代碼 – iOSDev 2010-10-27 07:25:14

+4

示例代碼:http://pastie.org/1254081 – 2010-10-27 23:02:58

+0

或者,您可以用克里斯的方法,以便更快的使用。上面的方法提供了更多的控制,並且可以通過您的(示例)詳細視圖控制器進行修改。 – 2010-10-27 23:04:28

5

使用此代碼

CGPoint location =[sender locationInView:self.tableView]; 
NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:location]; 
UITableViewCell *swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath]; 
NSIndexPath *indexPath = [self.tableView indexPathForCell:swipedCell]; 
7

獲取當前選定行。 如果您只有一個部分,可能會有所幫助。

- (NSUInteger)currentSellectedRowIndex 
{ 
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow]; 
    if (selectedIndexPath) { 
     return selectedIndexPath.row; 
    } 
    else { 
     return NSNotFound; 
    } 
}