[英]iOS - How to set a UISwitch programmatically
I want to set my UISwitch to on or off programmatically.我想以编程方式将我的 UISwitch 设置为打开或关闭。 How would I do that?
我该怎么做? I am an iOS newbie.
我是iOS新手。
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)
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 应用程序还是移动网站?
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";
}
I also use the setOn:animated:
for this and it works fine.我也使用
setOn:animated:
为此,它工作正常。 This is the code I use in an app's viewDidLoad
to toggle a UISwitch
in code so that it loads preset.这是我在应用程序的
viewDidLoad
用于切换代码中的UISwitch
以便加载预设的代码。
// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];
[self.autoplaySwitch setOn:autoPlayOn animated:NO];
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];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.