如何使用UISwitch创建UITableViewCell并获取数据?

eem*_*bee 32 iphone uitableview uiswitch

我有一个简单的问题.我在Interface Builder中创建了一个包含UISwitch的自定义UITableViewCell.

问题1:更简单,更好的方法吗?问题2:在UITableViewController中使用时,获取数据的最佳方法是什么?在某些时候,我需要通过表格并检查每个单元格的状态,或者在开关状态直接变化时发送一些反馈?

谢谢您的帮助.

Sau*_*h G 85

您可以UISwitch在附件视图中添加.这是最简单的方法,更不用说它看起来"优雅".

然后,在您的tableview控制器代码中,您可以在每次切换开关时调用选择器,甚至可以通过在控制器中获取开关的当前状态来切换开关本身.

如果您想要代码示例,请知道.

---示例代码---

- (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;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用一种方法根据模型中的更改更新开关.你可以使用你想要的任何东西 - 代表,通知,KVO等.

例:

- (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];
}

 }
Run Code Online (Sandbox Code Playgroud)

  • 关于示例代码,请注意一点.除非表中的每个单元都有一个开关,否则当重复使用单元时,代码将无法正常工作(因为单元标识符始终相同@"单元").如果您的UITableView具有其他类型的单元格(没有UISwitch),那么dequeReusableCellWithIdentifier可以返回没有UISwitch的单元格,在这种情况下,单元格将永远不会获得UISwitch,因为您只在创建新单元格时添加一个(即当cell == null时) .对于需要UISwitch的索引路径,您应该使用像@"SwitchCell"这样的唯一cellIdentifier. (2认同)

小智 8

Switch.tag = indexPath.row;
[Switch addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];



- (void)updateSwitchAtIndexPath:(UISwitch *)aswitch{
    FFLog(@"%i",aswitch.tag);
}
Run Code Online (Sandbox Code Playgroud)