Switch用于在打开和关闭状态之间切换。

Switches - 重要属性

  • onImage
  • offImage
  • on

Switches - 重要方法

- (void)setOn:(BOOL)on animated:(BOOL)animated

Switches - 自定义方法

-(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];
}

运行应用程序时,将获得以下输出-

iOS Tutorial

向右滑动Switch时,输出如下-

iOS Tutorial

参考链接

https://www.learnfk.com/ios/ios-ui-elements-switches.html