声明该类的对象:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController { //定义一个开关控件(开和关) //所有UIKit框架库中控件均已UI开头 //苹果官方的控件都定义在UIKit框架库中 UISwitch *_myswitch; } @property (nonatomic, strong) UISwitch *myswitch; @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController /** * 同步属性和成员变量 */ @synthesize myswitch = _myswitch; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //创建一个开关对象. _myswitch = [[UISwitch alloc]init]; //苹果官方的控件的位置设置 //位置x.y的值是可以改变的; //宽度和高度是无法改变的; _myswitch.frame = CGRectMake(100, 100, 80, 40); //开关状态设置 _myswitch.on = YES; //设置开关状态 // [_myswitch setOn:YES animated:YES]; [self.view addSubview:_myswitch]; //设置开启的颜色 [_myswitch setOnTintColor:[UIColor redColor]]; //设置圆钮颜色 [_myswitch setThumbTintColor:[UIColor blueColor]]; //设置整体风格 [_myswitch setTintColor:[UIColor purpleColor]]; //添加开关事件函数 [_myswitch addTarget:self action:@selector(SwChange:) forControlEvents:UIControlEventValueChanged]; } // - (void)SwChange:(UISwitch *)myswitch{ if (myswitch.on == YES) { NSLog(@"开关打开"); }else{ NSLog(@"开关关闭"); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. }
//他的一些属性和方法:
NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UISwitch : UIControl <NSCoding> @property(nullable, nonatomic, strong) UIColor *onTintColor NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR; @property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(6_0); @property(nullable, nonatomic, strong) UIColor *thumbTintColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; @property(nullable, nonatomic, strong) UIImage *onImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; @property(nullable, nonatomic, strong) UIImage *offImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; @property(nonatomic,getter=isOn) BOOL on; - (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER; // This class enforces a size appropriate for the control, and so the frame size is ignored. - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; - (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action @end NS_ASSUME_NONNULL_END