[Swift]UIKit学习之滑块控件UISlider的用法

UIKit学习之滑块控件UISlider的用法


Slider:

Sliders enable users to interactively modify some adjustable value in an app, such as speaker volume or screen brightness. 


UISlider:

A UISlider object is a visual control used to select a single value from a continuous range of values. Sliders are always displayed as horizontal bars. An indicator, or thumb, notes the current value of the slider and can be moved by the user to change the setting.


UISlider控件的创建:

(1) 在Stroyboard中使用Ctrl+Drag拖拽法创建

(2) 代码创建

//创建slider控件
let slider=UISlider(frame:CGRectMake(0,0,300,50))
//设置slider
slider.center=self.view.center
slider.minimumValue=0  //最小值
slider.maximumValue=1  //最大值
slider.value=0.5  //当前默认值
  
self.view.addSubview(slider)


设置UISlider控件的值:

Slider的值范围是0-1,是六位数的浮点数

slider.setValue(0.8,animated:true)

slider.minimumValue=0  //最小值
slider.maximumValue=1  //最大值


设置UISlider控件的边槽颜色:

//设置边槽的颜色
slider.minimumTrackTintColor=UIColor.redColor()   //左边槽的颜色,默认是蓝色的
slider.maximumTrackTintColor=UIColor.brownColor() //右边槽的颜色,默认是灰色的


代码示例:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let slider=UISlider(frame:CGRectMake(0,0,300,50))
        slider.center=self.view.center
        slider.minimumValue=0  //最小值
        slider.maximumValue=1  //最大值
        slider.value=0.5  //当前默认值
        
        slider.continuous=false  //滑块滑动停止后才触发ValueChanged事件
        
        //添加响应事件
        slider.addTarget(self, action:"sliderDidchanged:", forControlEvents:UIControlEvents.ValueChanged)
        
        //设置边槽的颜色
        slider.minimumTrackTintColor=UIColor.redColor()   //左边槽的颜色,默认是蓝色的
        slider.maximumTrackTintColor=UIColor.brownColor() //右边槽的颜色,默认是灰色的
        
        self.view.addSubview(slider)
        
    }

    
    //响应事件函数
    func sliderDidchanged(slider:UISlider){
        
        //输出控件的值
        print(slider.value)
        
        //设置Slider的值大小为0.8
        //slider.setValue(0.8, animated:true)
        //print(slider.value)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


开发环境:

Xcode Version 7.0 (7A220)


参考资料:

http://www.hangge.com/blog/cache/detail_536.html

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UISlider.html

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISlider_Class/index.html








你可能感兴趣的:(ios,swift,UIKit,UISlider)