我想以编程方式将我的UISwitch设置为开启或关闭。我该怎么办?我是iOS新手。
答案 0 :(得分:189)
我不熟悉iOS中的“复选框”,但是如果您使用的是UISwitch,那么正如开发人员API中所见,任务setOn: animated:
应该可以解决问题。
- (void)setOn:(BOOL)on animated:(BOOL)animated
因此,要在程序中将开关设置为ON,您可以使用:
<强>目标C 强>
[switchName setOn:YES animated:YES];
<强>夫特强>
switchName.setOn(true, animated: true)
答案 1 :(得分:25)
UISwitch有一个名为“on”的属性应该设置。
您是在谈论iOS应用程序还是移动网站?
答案 2 :(得分:9)
//使用此代码...... //解决iOS中交换机的开/关状态问题
- (IBAction)btnSwitched:(id)sender {
UISwitch *switchObject = (UISwitch *)sender;
if(switchObject.isOn){
self.lblShow.text=@"Switch State is Disabled";
}else{
self.lblShow.text=@"Switch State is Enabled";
}
答案 3 :(得分:2)
我也使用setOn:animated:
来做这件事并且工作正常。这是我在应用viewDidLoad
中使用的代码,用于在代码中切换UISwitch
以便加载预设。
// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];
[self.autoplaySwitch setOn:autoPlayOn animated:NO];
答案 4 :(得分:0)
的 ViewController.h 强>
- (IBAction)switchAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *lbl;
<强> ViewController.m 强>
- (IBAction)switchAction:(id)sender {
UISwitch *mySwitch = (UISwitch *)sender;
if ([mySwitch isOn]) {
self.lbl.backgroundColor = [UIColor redColor];
} else {
self.lbl.backgroundColor = [UIColor blueColor];
}
}