2010-09-01 88 views
2

我創建拖車或多個自定義單元格如何獲取indexPath.row /路徑當我單擊連接中的Switch?

每個單元都有內

我怎麼能知道哪個開關行中的一個開關我點擊

第Ex.I單擊第3行中切換,比它將返回indexPath.row = 3

並且開關狀態是打開還是關閉?

我應該投入哪些空白?

我知道有一種方法可以得到由indexpath回報:

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

但我不想碰的行,就在交換......

哦,我做了一些研究,但它只是有點不同

How can keep track of the index path of a button in a tableview cell?

什麼想法?

我希望我可以張貼我的屏幕截圖,但不是我一個新的用戶 系統不允許我這樣做

回答

3

當您創建的開關,建立目標和行動是:

[mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged]; 

在這裏,目標self是您的UITableViewController,其中您需要實施方法(void) switchToggled:(id)sender來處理控制事件。當切換時,交換機將自動將自己發送到switchToggled方法,作爲sender。像這樣(修改從你鏈接的UIButton爲例):

- (void)switchToggled:(id)sender { 
    UISwitch *theSwitch = (UISwitch *)sender; 
    UITableViewCell *cell = (UITableViewCell *)theSwitch.superview; 
    UITableView *tableView = (UITableView *)cell.superview; 
    NSIndexPath *indexPath = [tableView indexPathForCell:cell]; 

    if(theSwitch.on) { 
     // switch turned on 
    } 
    else { 
     // switch turned off 
    } 
} 
+0

嗯..它看起來可以工作!我現在試試吧! 謝謝!我該如何成爲像你這樣的優秀程序員? – 2010-09-02 01:33:27

+0

不好意思,我創建了一個LightCell0;而一個TableViewController,我不得不把這個代碼放在哪一個? – 2010-09-02 02:07:08

+0

請參閱http://stackoverflow.com/questions/18919616/uitableviewcell-indexpath-crash-in-ios7 iOS7。還有額外的表格視圖和單元格的包裝器。我不得不用: 'UITableViewCell * cell =(UITableViewCell *)switchControl.superview.superview; UITableView * tableView =(UITableView *)cell.superview.superview;' – joshs 2014-05-28 12:27:17

1

當在選擇按鈕創建

button.tag = [indexPath row] 

按鈕,拉排出來的標籤

int myRow = [(UIButton *)sender tag]; 
+0

我可以把這個[LightSwitch的addTarget:自我行動:@selector(switchlightswitch)forControlEvents:UIControlEventValueChanged] ??? – 2010-09-02 01:30:18