WalterBeiter
WalterBeiter

Reputation: 2364

changing the color of a custom drawing in swift 4

So I've got a slider that changes the hue value of a UIColor. I want my custom drawing to have exactly this color.

My custom drawing class looks like this:

class CircleView: UIView {

    var color = UIColor().white {
        didSet {
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {

        if let context = UIGraphicsGetCurrentContext() {
            context.addArc(center: CGPoint(x: bounds.midX, y: bounds.midY), radius: bounds.height / 2, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
            color.setFill()
            context.fillPath()
        }
    }

}

In my viewController, I have a property observer that should change the color of the circle, that my custom drawing class draws:

My properties:

private var hueValue: Float = 0.0 {
    didSet {
        color = UIColor(hue: CGFloat(hueValue), saturation: 1, brightness: 1, alpha: 1)
        backgroundView.backgroundColor = color
        circle.color = color
    }
}
var color = UIColor()
var circle = CircleView()

And my Action method:

@IBAction func colorSliderChanged(_ sender: UISlider) {
        hueValue = sender.value
}

The Action method changes the hue value which changes the color of the backgroundView. But it does not change the color of the circle. The circle stays white.

Any ideas?

Here is a Screenshot of the app: enter image description here

Upvotes: 0

Views: 1528

Answers (1)

DonMag
DonMag

Reputation: 77578

If you have a UIView added in your Storyboard, and you have set its Custom Class to CircleView, but you have not created an @IBOutlet connection to it, your code has no access to that view.

If you have var circle = CircleView() but you have not added that view to your view, nothing you change to circle will show up on screen.

In your storyboard, add your UIView, change its class to CircleView, and then ctrl-drag to create your @IBOutlet. Xcode will automatically set it to @IBOutlet weak var circle: CircleView!, and you can set its color (don't forget to remove the var circle = CricleView() line).

Upvotes: 1

Related Questions