【发布时间】:2011-12-09 15:06:24
【问题描述】:
我想以编程方式将我的 UISwitch 设置为打开或关闭。我该怎么做?我是 iOS 新手。
【问题讨论】:
标签: objective-c ios
我想以编程方式将我的 UISwitch 设置为打开或关闭。我该怎么做?我是 iOS 新手。
【问题讨论】:
标签: objective-c ios
如果您使用的是 UISwitch,那么正如在开发人员 API 中看到的那样,任务 setOn: animated: 应该可以解决问题。
- (void)setOn:(BOOL)on animated:(BOOL)animated
因此,要在程序中将开关设置为 ON,您可以使用:
Objective-C
[switchName setOn:YES animated:YES];
斯威夫特
switchName.setOn(true, animated: true)
【讨论】:
UISwitch 有一个应该设置的名为“on”的属性。
您指的是 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";
}
【讨论】:
UISwitch *switchObject = (UISwitch *)sender;
我也为此使用setOn:animated:,它工作正常。这是我在应用程序的viewDidLoad 中使用的代码,用于在代码中切换UISwitch,以便加载预设。
// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];
[self.autoplaySwitch setOn:autoPlayOn animated:NO];
【讨论】:
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];
}
}
【讨论】: