UISlider 滑動條
宣告資料
var redslider = UISlider()
var greenslider = UISlider()
var blueslider = UISlider()
var label = UILabel()
let WIDTH = UIScreen.main.bounds.size.width
viewDidLoad
背景顏色
view.backgroundColor = .black
UISlider
// 長寬 redslider.frame.size = CGSize(width: WIDTH - 40, height: 50) // 中心 redslider.center = CGPoint(x: WIDTH / 2, y: 75) // 背景顏色 redslider.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.5) // 滑動條右邊顏色 redslider.maximumTrackTintColor = .black // 滑動條左邊顏色 redslider.minimumTrackTintColor = .red // 滑桿顏色 redslider.thumbTintColor = .white // 最小 redslider.minimumValue = 0.0 // 最大 redslider.maximumValue = 255.0 // 不放手, 計數 redslider.isContinuous = true // 加入動作 redslider.addTarget(self, action: #selector(slideraction), for: .valueChanged) view.addSubview(redslider) // 重複相同動作, 建立greenslider greenslider.frame.size = CGSize(width: WIDTH - 40, height: 50) greenslider.center = CGPoint(x: WIDTH / 2, y: 125) greenslider.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.5) greenslider.maximumTrackTintColor = .black greenslider.minimumTrackTintColor = .green greenslider.thumbTintColor = .white greenslider.minimumValue = 0 greenslider.maximumValue = 255 greenslider.isContinuous = true greenslider.addTarget(self, action: #selector(slideraction), for: .valueChanged) view.addSubview(greenslider) // 重複相同動作, 建立blueslider blueslider.frame.size = CGSize(width: WIDTH - 40, height: 50) blueslider.center = CGPoint(x: WIDTH / 2, y: 175) blueslider.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.5) blueslider.maximumTrackTintColor = .black blueslider.minimumTrackTintColor = .blue blueslider.thumbTintColor = .white blueslider.minimumValue = 0 blueslider.maximumValue = 255 blueslider.isContinuous = true blueslider.addTarget(self, action: #selector(slideraction), for: .valueChanged) view.addSubview(blueslider)
UILabel(顯示數值)
label.frame.size = CGSize(width: WIDTH - 40, height: 50) label.center = CGPoint(x: WIDTH / 2, y: 225) label.text = "RGB 數值 ( red: 0, green: 0, blue: 0 )" label.textColor = .black label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 13) label.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.5) view.addSubview(label)
背景變色動作
func slideraction(sender: UISlider) {
let red = redslider.value
let green = greenslider.value
let blue = blueslider.value
view.backgroundColor = UIColor(red: CGFloat(red / 255), green: CGFloat(green / 255), blue: CGFloat(blue / 255), alpha: 1)
label.text = "RGB 數值 ( red: \(Int(red)), green: \(Int(green)), blue: \(Int(blue)) )"
}
下載完整範例 OneDrive