如何使用UISwitch创建UITableViewCell并获取数据? [英] How to create a UITableViewCell with a UISwitch and get the data?
问题描述
我有一个简单的问题。我在Interface Builder中创建了一个包含UISwitch的自定义UITableViewCell。
I have a simple problem. I created a custom UITableViewCell that includes a UISwitch in Interface Builder.
问题1:更简单,更好的方法吗?
问题2:在UITableViewController中使用时,获取数据的最佳方法是什么?在某些时候,我需要通过表格并检查每个单元格的状态,或者在开关状态直接变化时发送一些反馈?
Question 1: Easier, better way to do it ? Question 2: When used in an UITableViewController, what would be the best way to get the data ? At some point I either need to go through the table and check every cell about the status OR send some feedback when the status of the switches changes directly ?
感谢您的帮助。
推荐答案
您可以在附件视图中添加 UISwitch
。这是最简单的方法,更不用说它看起来优雅。
You could just add the UISwitch
in your accessory view. That is the easiest way to do it, not to mention that it looks 'elegant'.
然后,在您的tableview控制器代码中,您可以在每次切换开关时调用选择器,甚至可以通过获取开关的当前状态来切换开关本身控制器。
Then, in your tableview controller code, you could just call a selector every time the switch is toggled, or even toggle the switch itself by getting the switch's current status in your controller.
让我们知道您是否需要代码示例。
Let know if you'd like a code sample.
---示例代码 - -
---sample code---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//add a switch
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchview;
[switchview release];
}
cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
return cell;
}
然后,您可以使用一种方法根据您的更改更新交换机模型。您可以使用任何您想要的东西 - 代表,通知,KVO等。
Then, you could have a method that updates a switch based on changes in your model. You could use anything you want - delegates, notifications, KVO, etc.
示例:
- (void)updateSwitchAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
UISwitch *switchView = (UISwitch *)cell.accessoryView;
if ([switchView isOn]) {
[switchView setOn:NO animated:YES];
} else {
[switchView setOn:YES animated:YES];
}
}
这篇关于如何使用UISwitch创建UITableViewCell并获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!