UIView没有正确更改SWIFT的颜色值

时间:2015-07-25 04:17:37

标签: swift uicolor

我希望我的应用程序以视图中的颜色开始,但是当我将UIColor值添加到ViewDidLoad时,我将颜色更改为白色!而不是我想要添加的红色。这是我的代码,我已经检查了所有的代码但是我在swift中进行编程,所以我找不到一些没有完成工作的东西:

class RGBViewController: UIViewController {
    //Sldiers
     @IBOutlet weak var redSlider: UISlider!
     @IBOutlet weak var greenSlider: UISlider!
     @IBOutlet weak var blueSlider: UISlider!
     //Labels
     @IBOutlet weak var redLabel: UILabel!
     @IBOutlet weak var greenLabel: UILabel!
     @IBOutlet weak var blueLabel: UILabel!
     //View
     @IBOutlet weak var colorView: UIView!

    //set the thumb image
    func changeThumbImage() {
        let redThumb = UIImage(named: "RedSmall")
        redSlider?.setThumbImage(redThumb, forState: .Normal)
        let greenThumb = UIImage(named: "GreenSmall")
        greenSlider?.setThumbImage(greenThumb, forState: .Normal)
        let blueThumb = UIImage(named: "BlueSmall")
        blueSlider?.setThumbImage(blueThumb, forState: .Normal)
    }

    //VIEW DID LOAD
    override func viewDidLoad() {
        super.viewDidLoad()
        changeThumbImage()
        updateBackgroundColor()
        colorView.backgroundColor! = UIColor(red: 226, green: 67, blue: 67, alpha: 1)
    }

    func colorValues() {
        //assign the Int value to the labels
        redLabel?.text = String(stringInterpolationSegment: Int(redSlider.value * 255))
        greenLabel?.text = String(stringInterpolationSegment: Int(greenSlider.value * 255))
        blueLabel?.text = String(stringInterpolationSegment: Int(blueSlider.value * 255))
    }

    @IBAction func updateBackgroundColor() {
        colorValues()
        //safe unwrap the sliders and assign the view color
        if let red = redSlider, green = greenSlider, blue = blueSlider{
            let redValue = CGFloat(red.value)
            let greenValue = CGFloat(green.value)
            let blueValue = CGFloat(blue.value)

            colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1)
        }

    }


}

1 个答案:

答案 0 :(得分:3)

您必须将颜色值除以255

UIColor(red: 226/255.0, green: 67/255.0, blue: 67/255.0, alpha: 1.0)

你的行动也是:

@IBAction func updateBackgroundColor() {
    colorValues()
    let redValue = CGFloat(redSlider.value)
    let greenValue = CGFloat(greenSlider.value)
    let blueValue = CGFloat(blueSlider.value)

    colorView.backgroundColor = UIColor(red: redValue/255.0, green: greenValue/255.0, blue: blueValue/255.0, alpha: 1.0)
}

我创建了样本:

@IBOutlet var colorView: UIView!
@IBAction func chageSlider(sender: UISlider!) {
    println(sender.value)
    self.colorView.backgroundColor = UIColor(red: CGFloat(sender.value)/255.0, green: 0.0, blue: 0.0, alpha: 1.0)
}

changeSlidervalueChanged

UISlider行为

使用@IBAction

连接滑块

enter image description here

希望它对你有所帮助。