iOS,UISlider

iOS开发中,有时候会用到滑动条,考虑用UISlider控件,那么怎样做一个自己喜欢的滑动条呢,下面详细介绍:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong)UISlider * mySlider;
@property(nonatomic,assign)int temp;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 创建一个UISlider
    _mySlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 300, 10)];
    // 定位UISlider的位置
    _mySlider.center = self.view.center;
    // 设置UISlider的最小值和最大值
    _mySlider.minimumValue = 0;
    _mySlider.maximumValue = 100;
    // 设置UISlider的初始值
    _mySlider.value = 0;
    // 为UISlider添加事件方法
    [_mySlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    //设置自己喜欢的滑动条颜色
    UIColor *newColor=[UIColor colorWithRed:125/255.0f green:120/255.0f blue:86/255.0f alpha:1];
    _mySlider.backgroundColor=newColor;
    
    // 定义UISlider的样式
    _mySlider.minimumTrackTintColor = [UIColor clearColor];
    _mySlider.maximumTrackTintColor = [UIColor clearColor];
//    _mySlider.thumbTintColor = [UIColor whiteColor];
    //设置滑动的那个圆点的图片
    [_mySlider setThumbImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
    
    //设置圆角
    _mySlider.layer.cornerRadius=4;
    _mySlider.layer.masksToBounds=YES;
    
    // 将UISlider添加到一个UIView视图中
    [self.view addSubview:_mySlider];

    
}



- (void)sliderValueChanged:(id)sender
{
    if ([sender isKindOfClass:[UISlider class]])
    {
        UISlider * slider = (UISlider *)sender;
        if(fabs(slider.value-self.temp)>=8)
        {
            if(slider.value<=8)
            {
                slider.value=0;
            }
            else if(slider.value>=92)
            {
                slider.value=100;
            }
            self.temp=(int)slider.value;
            NSLog(@"可以发送请求%d",(int)slider.value);
        }
    
    }
}


@end

Demo地址:https://github.com/gujinyue1010/iOS_UISlider.git

你可能感兴趣的:(iOS,UISlider)