一、UISwithch屬性說明:
tintColor:
開關處于關閉狀態時邊框的顏色(注意這邊是邊框的顏色)
onTintColor:
開關處于開啟狀態時的顏色
thumbTintColor:
開關的狀態鈕顏色
onImage:
開關處于開啟狀態時的圖片(iOS7及之后設置無效)
offImage:
開關處于關閉狀態時的圖片(iOS7及之后設置無效)
backgroundColor:整個開關背景色,設置后可以明顯看到一個矩形背景
iOS系統內置了UISwithch控件的size,所以通過代碼調整UISwithch的大小無效.
默認大小 51.0f 31.0f
二、調整UISwitch 關閉狀態背景色
tintColor屬性 只能調整off狀態的邊框顏色像這樣:
-(UISwitch *)switchFunc{
if(_switchFunc == nil){
_switchFunc = [[UISwitch alloc]init];
[_switchFunc setTintColor:HEXCOLOR(0x99999)];
[_switchFunc setOnTintColor:HEXCOLOR(kBlueColor)];
[_switchFunc setThumbTintColor:[UIColor whiteColor]];
_switchFunc.layer.cornerRadius = 15.5f;
_switchFunc.layer.masksToBounds = YES;
[_switchFunc addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
}
return _switchFunc;
}
結果就像這樣
開啟狀態
關閉狀態
方法:
1.設置switch的背景色
2.設置圓邊角
細看你會發現右邊多了點,和我們要的效果不一樣
3.調整控件大小
49.0f, 31.0f
最終效果圖
OK
下面是核心代碼:
-(UISwitch *)switchFunc{
if(_switchFunc == nil){
_switchFunc = [[UISwitch alloc]init];
[_switchFunc setBackgroundColor:HEXCOLOR(0x999999)];
[_switchFunc setOnTintColor:HEXCOLOR(kBlueColor)];
[_switchFunc setThumbTintColor:[UIColor whiteColor]];
_switchFunc.layer.cornerRadius = 15.5f;
_switchFunc.layer.masksToBounds = YES;
[_switchFunc addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
}
return _switchFunc;
}
[_switchFunc mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.mas_equalTo(self.contentView);
make.size.mas_equalTo(CGSizeMake(49.0f, 31.0f));
make.right.mas_equalTo(self.contentView).with.offset(-12.0f);
}];
三、調整UISwitch 大小
setFrame 方法并不能更改它的大小。
UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectMake(200, 15, 50, 15)];
sw.transform = CGAffineTransformMakeScale( 0.5, 0.5);//縮放
1.1 CGAffineTransformMakeScale(CGFloat sx, CGFloat sy)
這個方法可以方便的對view的長和寬進行縮放,不改變view的中心點。注意!中心點不變指的是物理位置不變,不是坐標,因為坐標系此時已經發生改變
1.2 CGAffineTransformScale(CGAffineTransform t,CGFloat sx, CGFloat sy)
這個方法同樣是view的長和寬進行縮放,效果類似CGAffineTransformMakeScale(CGFloat sx, CGFloat sy)不同的是這個方法可以疊加其他CGAffineTransform效果(比如旋轉)
第三方庫
一個用圖片實現的switch庫,動態效果相對系統 差點,可定制性高
TTSwitch
一個比較有味的第三方庫
LLSwitch