2014-04-24 34 views
0

當用戶更改我的UISwitch的狀態時,我試圖打開/關閉。在原型單元中訪問UISwitch

enter image description here

例如

- (IBAction)toggleSwitch:(id)sender { 

    ChannelsTableViewCell* cell = (ChannelsTableViewCell *)[sender superview].superview; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

    if (cell.localSwitch.on) 
    { 
     NSLog(@"On"); 
    } 

} 

當我運行這個它拋出一個錯誤。

2014年4月24日11:33:41.462 HRApp [3258:60B] - [UITableViewCellScrollView localTitle]:無法識別的選擇發送到實例0x19354410 2014年4月24日11:33:41.467 HRApp [3258:60B] * **終止應用程序由於未捕獲的異常「NSInvalidArgumentException」,原因是:「 - [UITableViewCellScrollView localTitle]:無法識別的選擇發送到實例0x19354410」

回答

3

如果掛鉤的IBAction到交換機,則無需得到UITableViewCell檢查交換機的值。您可以使用IBAction中的sender參數。因此:

- (IBAction)toggleSwitch:(id)sender { 
    UISwitch *switch = (UISwitch *)sender; 
    if (switch.on) 
    { 
     NSLog(@"On"); 
    } 

} 

如果你需要找到在其中顯示了UISwitchindexPath,你可以添加以下內容:

CGPoint pointInTable = [switch convertPoint:switch.bounds.origin toView:self.tableView];  
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTable]; 
+0

完美地工作!最終,如果滑塊的狀態發生更改,我想更新數據庫中的值。如何從toggleSwitch操作獲取受影響的單元格的單元格標題(cell.localtTitle)或索引路徑行? – user2920762

+0

@ user2920762我用可能的解決方案編輯了答案,該解決方案將爲您提供發件人的indexPath。 – Cezar

+0

我編輯了我的答案。注意我現在將發件人投射到「UISwitch」並使用它。 – Cezar