iOS下UISlider的订制样式

近期项目要使用slider,需要做成的样式如下:


实现首先要创建一个继承UISlider的子类,因为改变滑条高度的函数只有在子类继承后才能生效,附上改变滑条高度的代码,在子类的.m文件里写:


-(CGRect)trackRectForBounds:(CGRect)bounds

{

bounds= [super trackRectForBounds:bounds];//必须通过调用父类的trackRectForBounds 获取一个 bounds 值,否则 Autolayout 会失效,UISlider 的位置会跑偏。returnCGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width,20);//这里面的20即为你想要设置的高度。}


这样滑条高度设置就完成了。

接下来是滑条的背景,实例化这个子类使用方法:

[_stateSld setMinimumTrackImage:[[UIImage imageNamed:@"sliderBack@2x"] stretchableImageWithLeftCapWidth:100topCapHeight:10] forState:(UIControlStateNormal)];//圆球左边的滑条背景[_stateSld setMaximumTrackImage:[UIImage imageNamed:@"sliderBack@2x"] forState:(UIControlStateNormal)];//圆球右边的滑条背景

因为这个滑条两边是有圆弧的,直接设置美工给的背景

左边角会出现加载不完全的情况,所以在图片设置使用了stretchableImageWithLeftCapWidth:topCapHeight:方法。


接下来给圆球加背景图,这里就贴下一个的,其他的根据value的值更改一下背景图就ok:

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderSmall"] forState:(UIControlStateNormal)];//普通情况圆球的背景图[_stateSld setThumbImage:[UIImage imageNamed:@"sliderSmall"] forState:(UIControlStateHighlighted)];//高亮状态圆球的背景图

在滑块滑动还有规定,只有这三个状态,不允许其他值得出现。这样先设置slider的滑动范围:

_stateSld.maximumValue =2;//滑块滑动最大值_stateSld.minimumValue =0;//滑块滑动最小值

值具体是多少的无所谓,三个状态我就准备是0,1,2这三个,你喜欢的话一万两万也无所谓。接下来还是很笨的办法,添加事件在事件里面写判断:


[_stateSld addTarget:self

action:@selector(valueChanged:)

forControlEvents:UIControlEventValueChanged];//给slider添加事件-(void)valueChanged:(UISlider *)sender {//round the slider position to the nearest index of the numbers arrayif(sender.value <0.5) {

sender.value=0;

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderSmall"] forState:(UIControlStateNormal)];

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderSmall"] forState:(UIControlStateHighlighted)];

}elseif(sender.value >0.5&& sender.value <1.5){

sender.value=1;

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderMid"] forState:(UIControlStateNormal)];

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderMid"] forState:(UIControlStateHighlighted)];

}else{

sender.value=2;

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderBig"] forState:(UIControlStateNormal)];

[_stateSld setThumbImage:[UIImage imageNamed:@"sliderBig"] forState:(UIControlStateHighlighted)];

}

}

这样就完成了。

你可能感兴趣的:(UI)