簡體   English   中英

如果我將UISwitch控件添加到每個表視圖單元格中,如何判斷它屬於哪個單元格?

[英]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方法中,你可以轉換傳入的UISwitchindexPathForCell superview (它是UITableViewCell本身),然后將它傳遞給tableViewindexPathForCell方法。

indexPathForCell將返回一個NSIndexPath對象,然后您可以使用該對象索引要修改的數據模型。 然后你要做的就是在tableView上調用reloadData

此外,在cellForRowAtIndexPath ,您應該根據您的模型設置UISwitch的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM