UISwitch详解

原文:https://www.jianshu.com/p/e6ef6eb04c6aios

1、UISwithch属性说明:

tintColor:
开关处于关闭状态时边框的颜色(注意这边是边框的颜色)
onTintColor:
开关处于开启状态时的颜色
thumbTintColor:
开关的状态钮颜色
onImage:
开关处于开启状态时的图片(iOS7及以后设置无效)
offImage:
开关处于关闭状态时的图片(iOS7及以后设置无效)
backgroundColor:整个开关背景色,设置后能够明显看到一个矩形背景

iOS系统内置了UISwithch控件的size,因此经过代码调整UISwithch的大小无效.git

默认大小 51.0f 31.0f

UISwitch详解

2、调整UISwitch 关闭状态背景色

tintColor属性 只能调整off状态的边框颜色像这样:github

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

结果就像这样ide

UISwitch详解

开启状态.net

UISwitch详解

关闭状态code

方法:
1.设置switch的背景色orm

UISwitch详解

2.设置圆边角blog

UISwitch详解

细看你会发现右边多了点,和咱们要的效果不同
3.调整控件大小图片

49.0f, 31.0f

UISwitch详解

最终效果图get

UISwitch详解

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

3、调整UISwitch 大小

引用如何设置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

UISwitch详解

一个比较有味的第三方库
LLSwitch

相关文章
相关标签/搜索