// // ViewController.swift // UISliderSample // // Created by jinnchang on 15/3/19. // Copyright (c) 2015年 Jinn Chang. All rights reserved. // import UIKit class ViewController: UIViewController { var mySlider: UISlider? override func viewDidLoad() { // 定义一个按钮,使 slider 复位 let button1 = UIButton.buttonWithType(.System) as? UIButton button1?.frame = CGRectMake(self.view.frame.width/2 - 100, 50, 200, 50) button1?.setTitle("reset", forState: UIControlState.Normal) button1?.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) button1?.tag = 1 // 定义一个按钮,获取当前 slider 的值 let button2 = UIButton.buttonWithType(.System) as? UIButton button2?.frame = CGRectMake(self.view.frame.width/2 - 100, 150, 200, 50) button2?.setTitle("get value", forState: UIControlState.Normal) button2?.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) button2?.tag = 2 // 定义一个 slider mySlider = UISlider(frame:CGRectMake(self.view.frame.width/2 - 100, 400, 200, 100)) // 设置滑块所能滚动到的最小值 mySlider?.minimumValue = 0 // 设置滑块所能滚动到的最大值 mySlider?.maximumValue = 100 // 设置默认值 mySlider?.value = 20 // 设置是否连续触发事件,如果设为 false,在滑动过程中不触发,如果设为 true,在滑动过程中会连续触发 mySlider?.continuous = true // 设置滑块左轨的图片 mySlider?.setMinimumTrackImage(UIImage(named: "track.png"), forState: UIControlState.Normal) // 设置滑块右轨的图片 mySlider?.setMaximumTrackImage(UIImage(named: "track.png"), forState: UIControlState.Normal) // 设置滑块的图片 mySlider?.setThumbImage(UIImage(named: "thumb.png"), forState: UIControlState.Normal) // 注意这里要加UIControlStateHightlighted的状态,否则当拖动滑块时滑块将变成原生的控件 mySlider?.setThumbImage(UIImage(named: "thumb.png"), forState: UIControlState.Highlighted) // 设置 slider 左侧图片 mySlider?.minimumValueImage = UIImage(named: "min.png") // 设置 slider 右侧图片 mySlider?.maximumValueImage = UIImage(named: "min.png") // 添加控制事件 mySlider?.addTarget(self,action:Selector("sliderValueChange:"), forControlEvents: UIControlEvents.ValueChanged) mySlider?.addTarget(self,action:Selector("sliderDragUp:"), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button1!) self.view.addSubview(button2!) self.view.addSubview(mySlider!) } /// 按钮响应事件 func buttonAction(sender: UIButton) { var num = sender.tag switch num { case 1: if(mySlider?.value != 20){ mySlider?.setValue(20, animated: true) } case 2: println("value:\(mySlider!.value)") default: break } } /// 滑块拖动时的事件 func sliderValueChange(sender: UISlider) { println("value:\(sender.value)") } /// 滑块拖动后的事件 func sliderDragUp(sender: UISlider) { println("value:\(sender.value)") } }------------------------------------------------------------------------------------------
文章最后更新时间:2015年3月20日09:54:24。参考资料如下:
UIKit User
Interface Catalog: Sliders
原文地址:http://blog.csdn.net/jinnchang/article/details/44487407