iOS 控制元件之 UISlider

征途LN發表於2014-02-19

UISlider繼承UIControl,是一個可以在最小值和最大值之間任意滑動的進度條,和UIProgressView的區別在於:前前者無法響應使用者的觸控事件,而後者可以。

我下了一個demo,相信的總結了一下UISlider 的使用方法

//
//  ViewController.m
//  UIProgressViewDemo
//
//  Created by 冷凝 on 14-2-19.
//  Copyright (c) 2014年 **. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
   // UIProgressView * _progressView;
    UISlider * _slider;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addSlider];
    //[self addProgressView];
}

-(void)addSlider{
    _slider = [[UISlider alloc]initWithFrame:CGRectMake(10, 10, 300, 50)];
    _slider.minimumValue = 0;
    _slider.maximumValue = 100;
    _slider.value = 50;
    _slider.minimumValueImage = [UIImage imageNamed:@"meigui.png"];
    _slider.maximumValueImage = [UIImage imageNamed:@"yongbao.png"];
    _slider.minimumTrackTintColor = [UIColor blackColor];
    //_slider.maximumTrackTintColor = [UIColor greenColor];
    _slider.thumbTintColor = [UIColor orangeColor];
    [_slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [_slider setThumbImage:[UIImage imageNamed:@"daku.png"] forState:UIControlStateNormal];//設定預設圖片
    [_slider setThumbImage:[UIImage imageNamed:@"chouyan.png"] forState:UIControlStateHighlighted];//設定移動時顯示進度的圖片

    [self.view addSubview:_slider];
}

//根據值的變化來做判斷
-(void)sliderValueChanged:(UISlider*)slider{
    if (slider.value <= slider.maximumValue/2.0) {
        slider.minimumTrackTintColor = [UIColor blackColor];
        
    }else{
        [slider setValue:90 animated:YES];
        slider.minimumTrackTintColor = [UIColor redColor];
        slider.maximumTrackTintColor = [UIColor blackColor];
    }
}


為了供子類定製還提供了四個方法:看到函式名就知道函式的功能

// lets a subclass lay out the track and thumb as needed
- (CGRect)minimumValueImageRectForBounds:(CGRect)bounds;
- (CGRect)maximumValueImageRectForBounds:(CGRect)bounds;
- (CGRect)trackRectForBounds:(CGRect)bounds;
- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value;


相關文章