2010-09-10 62 views

回答

48
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    // now you can use cell.textLabel.text 
} 
3

可以使用獲得的細胞[self.tableView的cellForRowAtIndexPath:],然後訪問其textLabel.text屬性,但通常有一種更好的方式。

通常你已經基於你的UITableViewController有權訪問的模型數組填充你的表。因此,在大多數情況下處理此問題的更好方法是獲取所選單元格的行號,並使用該單元格查找模型中的關聯數據。

例如,假設您的控制器具有Buddy對象,其中有一個name屬性的數組:

NSArray *buddies; 

通過運行一個查詢或東西來填充這個數組。然後在tableView:cellForRowAtIndexPath:您構建基於每個好友的名稱表視圖單元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BuddyCell"]; 
    if (!cell) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BuddyCell"] autorelease]; 
    } 
    cell.textLabel.text = [buddies objectAtIndex:indexPath.row]; 
    return cell; 
} 

現在,當用戶選擇一排,你只是拉相應的好友對象你的陣列,並用它做什麼。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    Buddy *myBuddy = [buddies objectAtIndex:indexPath.row]; 
    NSLog (@"Buddy selected: %@", myBuddy.name); 
} 
+0

那是什麼,我試圖做的,但我只是沒想到FO的NSArray的事情。 – lab12 2010-09-10 15:21:09

+0

很酷。我可以根據你的問題說出這可能是一個更清晰的方式來實現你正在嘗試做的事情。 – cduhn 2010-09-10 15:43:18

1
if (selected) 
{ 
    indicator.image = [UIImage imageNamed:@"IsSelected.png"]; 
    [arrSlectedItem addObject:strselecteditem]; 
    NSLog(@"-- added name is %@", strselecteditem); 

} 
else 
{ 
    indicator.image = [UIImage imageNamed:@"NotSelected.png"]; 
    [arrSlectedItem removeObject:strselecteditem]; 
    NSLog(@"--- remove element is -- %@", strselecteditem); 
} 
0

如果有人碰到這個蹣跚,並想知道如何在迅速做到這一點的代碼如下。還請記住使用可選綁定來展開可選項,並且還要避免打印出「可選(」Tapped Item Label「)」。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     let cell = tableView.cellForRowAtIndexPath(indexPath) 

     // Unwrap that optional 
     if let label = cell?.textLabel?.text { 
      println("Tapped \(label)") 
     } 
    } 
0

我這裏使用的是什麼,很簡單

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){ 

    if editingStyle == UITableViewCellEditingStyle.Delete 
    { 

     //create cellobj with indexpath for get it text 
     let cell = tableView.cellForRowAtIndexPath(indexPath) 
     let celltext = (cell?.textLabel?.text!)! as String 
     //do what ever you want with value 
     print((cell?.textLabel?.text!)! as String) 



    } 
} 
相關問題