let slider = UISlider(frame: CGRectMake(10.0,10.0, (CGRectGetWidth(self.view.bounds) - 10.0 * 2), 20.0))self.view.addSubview(slider)slider.backgroundColor = UIColor.lightGrayColor()
// 設定值(預設值為0.0,且值區間為0.0~1.0)slider.minimumValue = 1.0slider.maximumValue = 100.0slider.setValue(20.0, animated: true)
// 注意:滑動條大小值(minimumTrackTintColor、maximumTrackTintColor)顏色與大小值左右兩端表徵圖(minimumValueImage、maximumValueImage)不能同時設定,否則表徵圖設定無效slider.minimumValueImage = UIImage(named: "normalImage")slider.maximumValueImage = UIImage(named: "hightImage")
// 注意:滑動條大小值顏色(minimumTrackTintColor、maximumTrackTintColor)與滑動條大小值表徵圖(setMinimumTrackImage、setMaximumTrackImage)不能同時設定,否則先設定的無效// slider.setMinimumTrackImage(UIImage(named: "normalImage"), forState: UIControlState.Normal)// slider.setMaximumTrackImage(UIImage(named: "hightImage"), forState: UIControlState.Normal) slider.minimumTrackTintColor = UIColor.yellowColor()slider.maximumTrackTintColor = UIColor.redColor()
// 滑動塊顏色、或表徵圖設定(注意:兩者不能同時設定,否則先設定的無效。另外,預設thumb塊比較大,可通過設定thumbImage的方法改變thumb大小)slider.thumbTintColor = UIColor.greenColor()slider.setThumbImage(UIImage(named: "hightImage"), forState: UIControlState.Normal)slider.setThumbImage(UIImage(named: "hightImage"), forState: UIControlState.Highlighted)
// 滑塊滑動停止後才觸發ValueChanged事件slider.continuous = false// 響應事件slider.addTarget(self, action: Selector("sliderValueChange:"), forControlEvents: UIControlEvents.ValueChanged)
let label = UILabel(frame: CGRectMake(10.0, (CGRectGetMinY(slider.frame) + CGRectGetHeight(slider.bounds) + 10.0), (CGRectGetWidth(self.view.frame) - 10.0 * 2), 30.0))self.view.addSubview(label)label.backgroundColor = UIColor.yellowColor()label.textColor = UIColor.redColor()label.tag = 1000let value = slider.valuelabel.text = String(format: "slider當前值是:%.2f", arguments: [value])
// MARK: - sliderValueChangefunc sliderValueChange(slider:UISlider){ let value = slider.value let label:UILabel = self.view.viewWithTag(1000) as! UILabel label.text = String(format: "slider當前值是:%.2f", arguments: [value]) print("slider當前值是:\(value)")}
源碼:https://github.com/potato512/SYSwiftLearning