用三个滑竿去改变视图的颜色,分别是红绿蓝。

用UISlider来改变视图的颜色

  • 定义三个全局变量
var redslider : UISlider! = nil
var greenslider : UISlider! = nil
var blueslider : UISlider! = nil
  • 下面是具体代码
self.redslider = UISlider(frame: CGRect(x: 50, y: 100, width: 300, height: 40))
        self.view.addSubview(redslider)
        //最小值和最大值
        redslider.minimumValue = 0
        redslider.maximumValue = 255
        redslider.addTarget(self, action: #selector(sliderAction(slider:)), for: .valueChanged)
        redslider.thumbTintColor = UIColor.red
        
        self.greenslider = UISlider(frame: CGRect(x: 50, y: 200, width: 300, height: 40))
        self.view.addSubview(greenslider)
        greenslider.minimumValue = 0
        greenslider.maximumValue = 255
        greenslider.addTarget(self, action: #selector(sliderAction(slider:)), for: .valueChanged)
        greenslider.thumbTintColor = UIColor.green
        
            self.blueslider = UISlider(frame: CGRect(x: 50, y: 300, width: 300, height: 40))
        self.view.addSubview(blueslider)
        blueslider.minimumValue = 0
        blueslider.maximumValue = 255
        blueslider.addTarget(self, action: #selector(sliderAction(slider:)), for: .valueChanged)
        blueslider.thumbTintColor = UIColor.blue
        
      }

    func sliderAction (slider:UISlider) {
        self.view.backgroundColor = UIColor(red:CGFloat(self.redslider.value) / 255.0,green:CGFloat(self.greenslider.value) / 255.0,blue:CGFloat(self.blueslider.value) / 255.0,alpha:1)
}
  • 最后。实现分别改变视图的颜色为红色,绿色。蓝色。最后又变回白色

你可能感兴趣的:(用三个滑竿去改变视图的颜色,分别是红绿蓝。)