ios 自定义UISwitch

ios 自定义UISwitch 效果图如下:

自定义UISwitchOff
自定义UISwitchOn

1.定义两个UILable和一个UISwitch

@property (strong, nonatomic) UISwitch *costom;

@property (strong, nonatomic) UILabel *label;

@property (strong, nonatomic) UILabel *offLabel;


self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 31)];
    
    self.label.textAlignment = NSTextAlignmentCenter;
    [self.label setFont:[UIFont systemFontOfSize:7]];
    [self.label setText:@"显示"];
    [self.offLabel setHidden:false];

self.offLabel = [[UILabel alloc] initWithFrame:CGRectMake(49 -28, 0, 30, 31)];
    
    self.offLabel.textAlignment = NSTextAlignmentCenter;
    [self.offLabel setFont:[UIFont systemFontOfSize:8]];
    [self.offLabel setText:@"隐藏"];
    [self.offLabel setHidden:true];


//我这里switch控件宽高各放大了1.5倍,具体大小看需求
self.costom = [[UISwitch alloc] initWithFrame:CGRectMake(200, 200, 49, 31)];
    self.costom.transform = CGAffineTransformMakeScale(1.5, 1.5);
    [self.costom setOnTintColor:[UIColor orangeColor]];

2. 把两个label添加进switch 因为switch只是放大的显示,他本身的点击区域并没有变化 所以还需要再创建一个button添加进switch来响应他

//button点击方法
- (void) switchOnClick{
    if (self.costom.isOn) {
        [self.label setHidden:false];
        [self.offLabel setHidden:true];
        [self.costom setOn:false animated:true];
    }else{
        [self.label setHidden:true];
        [self.offLabel setHidden:false];
        [self.costom setOn:true animated:true];
    }
}


	[self.costom addSubview:self.label];
    
	[self.costom addSubview:self.offLabel];

	UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.costom.frame.size.width, self.costom.frame.size.height)];
    
    [btn addTarget:self action:@selector(switchOnClick) forControlEvents:UIControlEventTouchUpInside];
    

[self.view addSubview:self.costom];

就可以看到效果了

发布了7 篇原创文章 · 获赞 4 · 访问量 297

猜你喜欢

转载自blog.csdn.net/qq_41586150/article/details/103941731