iOS - 开关 开关的使用 开关用于在开和关状态之间切换。 重要属性 onImage offImage on 重要方法 - (void)setOn:(BOOL)on animated:(BOOL)animated 复制 添加自定义方法 addSwitch 和切换 -(IBAction)switched:(id)sender { NSLog(@"Switch current state %@", mySwitch.on ? @"On" : @"Off"); } -(void)addSwitch { mySwitch = [[UISwitch alloc] init]; [self.view addSubview:mySwitch]; mySwitch.center = CGPointMake(150, 200); [mySwitch addTarget:self action:@selector(switched:) forControlEvents:UIControlEventValueChanged]; } 复制 更新 ViewController.m 中的 viewDidLoad 如下 - (void)viewDidLoad { [super viewDidLoad]; [self addSwitch]; } 复制 输出 当我们运行应用程序时,我们将获得以下输出 - 向右滑动开关,输出如下 -