正如分段控件代替了單選按鈕,開關也代替了點選框,一般來說我的和設置頁面經(jīng)常常需要這種開關的需求,我們就來看看吧!
switch在UIKit框架之下,繼承自UIControl,可以添加觸發(fā)事件。開關狀態(tài)下默認的樣式如下.

點進去UISwitch,可以發(fā)現(xiàn)switch有以下的屬性和方法:
屬性:
onTintColor UIColor 開狀態(tài)下的顏色tintColor UIColor 關狀態(tài)下的顏色thumbTintColor UIColor 滑塊顏色onImage UIImage 無效offImage UIImage 無效on( isOn) BOOL isOn是用來獲取狀態(tài)的是get方法,on可以用來設置開關方法:
- (instancetype)initWithFrame:(CGRect)frame; // This class enforces a size apPRopriate for the control, and so the frame size is ignored.它有默認size,因此frame的size可以忽略,即使你定制了size系統(tǒng)也會忽略掉。- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action??:雖然系統(tǒng)默認switch的size,但是switch的size也不是不能變的,我們可以通過縮放來改變switch的大小,如果還是不能滿足你的需求,那你就需要自定義啦!Objective-C代碼:
//2. create switch self.mainSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 70, 0, 0)]; [self.view addSubview:self.mainSwitch]; //縮小或者放大switch的size self.mainSwitch.transform = CGAffineTransformMakeScale(0.5, 0.5); self.mainSwitch.layer.anchorPoint = CGPointMake(0, 0.3);// self.mainSwitch.onImage = [UIImage imageNamed:@"on.png"]; //無效// self.mainSwitch.offImage = [UIImage imageNamed:@"off.png"]; //無效// self.mainSwitch.backgroundColor = [UIColor yellowColor]; //它是矩形的 // 設置開關狀態(tài)(默認是 關)// self.mainSwitch.on = YES; [self.mainSwitch setOn:YES animated:true]; //animated //判斷開關的狀態(tài) if (self.mainSwitch.on) { NSLog(@"switch is on"); } else { NSLog(@"switch is off"); } //添加事件監(jiān)聽 [self.mainSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged]; //定制開關顏色UI //tintColor 關狀態(tài)下的背景顏色 self.mainSwitch.tintColor = [UIColor redColor]; //onTintColor 開狀態(tài)下的背景顏色 self.mainSwitch.onTintColor = [UIColor yellowColor]; //thumbTintColor 滑塊的背景顏色 self.mainSwitch.thumbTintColor = [UIColor blueColor];swift代碼:
//2. create switch mainSwitch = UISwitch(frame: CGRect(x: 100, y: 100, width: 0, height: 0)) view.addSubview(self.mainSwitch) //縮小或者放大switch的size mainSwitch.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) mainSwitch.layer.anchorPoint = CGPoint(x:0, y:0.3) mainSwitch.onImage = UIImage(named:"on.png") //無效 mainSwitch.offImage = UIImage(named:"off.png") //無效// mainSwitch.backgroundColor = UIColor.yellow //設置背景顏色之后才發(fā)現(xiàn)原來它是矩形的 // 設置開關狀態(tài)(默認是 關)// self.mainSwitch.isOn = true; mainSwitch.setOn(true, animated: true) // animated //判斷switch的開關狀態(tài) if mainSwitch.isOn { print("switch is on") } else { print("switch is off") } //添加監(jiān)聽事件 mainSwitch.addTarget(self, action: #selector(switchAction), for: .valueChanged) //定制開關顏色UI //tintColor 關狀態(tài)下的背景顏色 mainSwitch.tintColor = UIColor.red; //onTintColor 開狀態(tài)下的背景顏色 mainSwitch.onTintColor = UIColor.yellow; //thumbTintColor 滑塊的背景顏色 mainSwitch.thumbTintColor = UIColor.blue;當然,有的項目里的開關UI需要自定義字體或者自定義圖片,那么就需要自己自定義switch啦!
新聞熱點
疑難解答
圖片精選