【发布时间】:2011-04-03 04:49:41
【问题描述】:
我想在 iphone 应用程序中设置一个使用拨动开关来打开或关闭某些东西的设置。我看过教程,但它们只显示了如何在 iPhone 的设置位置执行此操作。我希望在应用程序中完成此操作。任何指南,帮助建议。我要找类似下图的东西。
【问题讨论】:
标签: iphone objective-c ios4 iphone-sdk-3.0
我想在 iphone 应用程序中设置一个使用拨动开关来打开或关闭某些东西的设置。我看过教程,但它们只显示了如何在 iPhone 的设置位置执行此操作。我希望在应用程序中完成此操作。任何指南,帮助建议。我要找类似下图的东西。
【问题讨论】:
标签: iphone objective-c ios4 iphone-sdk-3.0
您可以将 UISwitch 用作附件视图。这看起来(几乎?)和你的照片一模一样。
类似这样的:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
[mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = mySwitch;
}
// configure cell
UISwitch *mySwitch = (UISwitch *)cell.accessoryView;
mySwitch.on = YES; // or NO
cell.textLabel.text = @"Auto Connect";
return cell;
}
- (IBAction)switchToggled:(UISwitch *)sender {
UITableViewCell *cell = (UITableViewCell *)[sender superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSLog(@"Switch %i,%i toggled", indexPath.section, indexPath.row);
}
【讨论】:
您可以使用 UISwitch。这是非常简单的类参考指南。
基本上你可以通过检查它的“on”属性来检查它的状态。
if(mySwitch.on) {
//do something here
}
【讨论】:
首先,确保你的 UITableView 样式设置为“Grouped”
然后,在您的 cellForRowAtIndexPath 方法中,执行以下操作:
if (indexPath.section == kSwitchSection) {
if (!randomControl) {
randomControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
[randomControl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
randomLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,8,180,30)];
[randomLabel setFont:[UIFont boldSystemFontOfSize:16]];
[randomLabel setText:@"My Label"];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell addSubview:randomControl];
[cell addSubview:randomLabel];
}
记得稍后释放 UISwitch 对象,并包含根据它应该处于什么状态将其设置为打开或关闭的代码。
【讨论】: