如何在UITableView
单元上嵌入UISwitch
?示例可以在设置菜单中看到。UITableView单元中的UISwitch
我目前的解决方案:
UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;
如何在UITableView
单元上嵌入UISwitch
?示例可以在设置菜单中看到。UITableView单元中的UISwitch
我目前的解决方案:
UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
cell.accessoryView = mySwitch;
将其设置为accessoryView通常是要走的路。您可以在tableView:cellForRowAtIndexPath:
中进行设置您可能希望在切换开关时使用目标/操作来执行某些操作。像这样:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
switch([indexPath row]) {
case MY_SWITCH_CELL: {
UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];
if(aCell == nil) {
aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
aCell.textLabel.text = @"I Have A Switch";
aCell.selectionStyle = UITableViewCellSelectionStyleNone;
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
aCell.accessoryView = switchView;
[switchView setOn:NO animated:NO];
[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchView release];
}
return aCell;
}
break;
}
return nil;
}
- (void)switchChanged:(id)sender {
UISwitch *switchControl = sender;
NSLog(@"The switch is %@", switchControl.on ? @"ON" : @"OFF");
}
您可以添加UISwitch或任何其他控制单元的accessoryView
。这样它会出现在单元格的右侧,这可能是你想要的。
您可以在Interfacebuilder中准备单元格,将其链接到ViewController的IBOutlet,并在tableview要求正确的行时将其返回。
相反,您可以为单元格创建一个单独的xib(再次使用IB),并在创建单元格时使用UINib加载它。
最后,您可以通过编程方式创建开关并将其添加到您的单元格contentview或accessoryview。
哪一个最适合你,主要取决于你喜欢做什么。如果你的桌面内容是固定的(对于设置页面等),前两个可能工作得很好,如果内容是动态的,我更喜欢编程解决方案。请更具体地说明你想做什么,这会让你更容易回答你的问题。
我更喜欢编程解决方案(尽管它是设置页面),但我也对前两个选项的工作方式感兴趣。也许你可以更详细地解释一下它们。 – testing 2010-09-22 17:11:34
if (indexPath.row == 0) {//If you want UISwitch on particular row
UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[cell addSubview:theSwitch];
cell.accessoryView = theSwitch;
}
你目前的做法有什么问题吗? – MobileMon 2013-08-26 15:14:05