又做完一个项目,遂到了写帖时间了,要跟大家分享的是:自定义UISlider的图片和滑块,先看一下效果:
然后是实现了,我们使用的是UISlider的setMinimumTrackImage,和setMaximumTrackImage方法来定义图片
的,这两个方法可以设置滑块左边和右边的图片的,不过如果用的是同一张图片且宽度和控件宽度基本一致,就不会有变形拉伸的后果,先看代码,写在
viewDidLoad中:
//左右轨的图片
UIImage *stetchLeftTrack= [UIImage imageNamed:@"brightness_bar.png"];
UIImage *stetchRightTrack = [UIImage imageNamed:@"brightness_bar.png"];
//滑块图片
UIImage *thumbImage = [UIImage imageNamed:@"mark.png"];
UISlider *sliderA=[[UISlider alloc]initWithFrame:CGRectMake(30, 320, 257, 7)];
sliderA.backgroundColor = [UIColor clearColor];
sliderA.value=1.0;
sliderA.minimumValue=0.7;
sliderA.maximumValue=1.0;
[sliderA setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[sliderA setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
//注意这里要加UIControlStateHightlighted的状态,否则当拖动滑块时滑块将变成原生的控件
[sliderA setThumbImage:thumbImage forState:UIControlStateHighlighted];
[sliderA setThumbImage:thumbImage forState:UIControlStateNormal];
//滑块拖动时的事件
[sliderA addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
//滑动拖动后的事件
[sliderA addTarget:self action:@selector(sliderDragUp:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sliderA];