[英]If I add a UISwitch control to each of my table view cells, how can I tell which cell it belongs to?
我有一個UITableView
與包含UISwitch
控件的單元格。 它類似於下面顯示的iPhone時鍾應用程序中的表格視圖......
(來源: epicself.com )
在我的應用程序的cellForRowAtIndexPath
方法中,我創建並附加UISwitch
控件,如此...
CGRect frameSwitch = CGRectMake(215.0, 10.0, 94.0, 27.0);
UISwitch *switchEnabled = [[UISwitch alloc] initWithFrame:frameSwitch];
[switchEnabled addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchEnabled;
我的問題是,當用戶切換開關並調用switchToggled
方法時,如何判斷它屬於哪個表格單元? 如果不了解它的背景,我真的無法做很多事情。
非常感謝您的幫助!
首先,修復內存泄漏:
UISwitch *switchEnabled = [[[UISwitch alloc] initWithFrame:frameSwitch] autorelease];
然后選擇以下選項之一:
switchEnabled.tag = someInt; // before adding it to the cell
NSLog(@"switched %d",switch.tag); // to see which switch was toggled
要么
UITableViewCell *parentCell = switchEnabled.superview;
// + some magic to see which cell this actually is
在你的action方法中,你可以轉換傳入的UISwitch
的indexPathForCell
superview
(它是UITableViewCell
本身),然后將它傳遞給tableView
的indexPathForCell
方法。
indexPathForCell
將返回一個NSIndexPath
對象,然后您可以使用該對象索引要修改的數據模型。 然后你要做的就是在tableView
上調用reloadData
。
此外,在cellForRowAtIndexPath
,您應該根據您的模型設置UISwitch
的狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.