iOS - 如何以编程方式设置 UISwitch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7799760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS - How to set a UISwitch programmatically
提问by Suchi
I want to set my UISwitch to on or off programmatically. How would I do that? I am an iOS newbie.
我想以编程方式将我的 UISwitch 设置为打开或关闭。我该怎么做?我是iOS新手。
回答by Andrew_L
If you are using a UISwitch, then as seen in the developer API, the task setOn: animated:
should do the trick.
如果您正在使用 UISwitch,那么正如在开发人员 API 中看到的那样,该任务setOn: animated:
应该可以解决问题。
- (void)setOn:(BOOL)on animated:(BOOL)animated
So to set the switch ON in your program, you would use:
因此,要在您的程序中将开关设置为 ON,您可以使用:
Objective-C
目标-C
[switchName setOn:YES animated:YES];
Swift
迅速
switchName.setOn(true, animated: true)
回答by NWCoder
UISwitches have a property called "on" that should be set.
UISwitches 有一个名为“on”的属性应该被设置。
Are you talking about an iOS app or a mobile web site?
您是在谈论 iOS 应用程序还是移动网站?
回答by Anand Kr. Avasthi
Use this code to solve on/off state problem in switch in iOS
使用此代码解决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";
}
回答by Mike Critchley
I also use the setOn:animated:
for this and it works fine. This is the code I use in an app's viewDidLoad
to toggle a UISwitch
in code so that it loads preset.
我也使用setOn:animated:
这个,它工作正常。这是我在应用程序中viewDidLoad
用于切换UISwitch
代码以加载预设的代码。
// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];
[self.autoplaySwitch setOn:autoPlayOn animated:NO];
回答by Acharya Ronak
ViewController.h
视图控制器.h
- (IBAction)switchAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *lbl;
ViewController.m
视图控制器.m
- (IBAction)switchAction:(id)sender {
UISwitch *mySwitch = (UISwitch *)sender;
if ([mySwitch isOn]) {
self.lbl.backgroundColor = [UIColor redColor];
} else {
self.lbl.backgroundColor = [UIColor blueColor];
}
}