2010-12-14 91 views
17

我在每個單元格上都有一些名稱的tableview,如何在選擇行時獲得該名稱?如何獲得在UITableview中選擇的行的標題

我知道,我必須使用委託方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

,但我怎樣才能得到該行的這個稱號?

在此先感謝

問候

+0

行沒有標題。你想做什麼? – 2010-12-14 21:16:12

+0

我的意思是每個單元格在UItableview – appleDE 2010-12-14 21:22:48

回答

54
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; 
    NSString *cellText = selectedCell.textLabel.text; 
} 

該片段檢索所選單元格,並將其text屬性存儲在NSString中。


然而,我不推薦這種。最好將數據和表示層分開。使用後臺數據存儲(例如數組)並使用傳入的對象(例如,用於訪問數組的索引)中的數據訪問它。該數據存儲將與用於填充表的數據存儲相同。

+0

太棒了!非常感謝。 – iDev 2014-08-05 19:51:42

9

假設你使用的是標準的UITableViewCell,您可以通過使用

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 

然後通過訪問text屬性視圖屬性獲取細胞:

cell.textLabel.text 
cell.detailTextLabel.text 
+0

這是做什麼? :-) – Eiko 2010-12-14 21:20:13

+0

是的它是做什麼的? – appleDE 2010-12-14 21:23:18

+0

(+1)即使是小的錯字錯誤,對我也有用。在代碼中它是UITableViewCell,並且您編寫了UITableView(但是您在上面的文本中正確地編寫了它。 – HpTerm 2012-09-13 21:04:45

2

一旦通過UITableView委託屬性將您的某個類註冊爲委託,您只需實現tableView:didSelectRowAtIndexPath:方法,該方法將在用戶選擇行時調用。 (有關詳細信息,請參見UITableViewDelegate Protocol Reference。)

然後,您可以從中提取選定單元格通過標籤文本...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
     NSString *cellLabelText = cell.textLabel.text; 
    } 

..如果這是你需要真的是。

3

您可以使用以下(uitableview-)函數訪問uitabelview的每一行:

cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 

的方式,訪問您的tableview其他方法比的UITableView的委託方法,你必須把它掛在IB(例如..)

希望它有助於

0
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 

    NSString *rowTitle=[tableView cellForRowAtIndexPath:indexPath].textLabel.text; 
} 

這裏,

[tableView cellForRowAtIndexPath:indexPath]爲您提供選定的單元格,然後.textLabel.text爲您提供該單元格的標籤。