在swift 4

时间:2018-04-03 12:55:22

标签: ios swift drawing

所以我有一个滑块可以改变UIColor的色调值。我希望我的自定义绘图具有这种颜色。

我的自定义绘图类如下所示:

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()
        }
    }

}

在我的viewController中,我有一个属性观察器,它应该改变我自定义绘图类绘制的圆的颜色:

我的属性:

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()

我的行动方法:

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

Action方法更改了更改backgroundView颜色的hue值。但它不会改变圆圈的颜色。圆圈保持白色。

有什么想法吗?

以下是该应用的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:1)

如果您的故事板中添加了UIView,并且您已将自定义类设置为CircleView,但您创建了@IBOutlet连接对它来说,你的代码无法访问该视图。

如果您有var circle = CircleView()但尚未将那个视图添加到视图中,则您更改为circle的任何内容都不会显示在屏幕上。

在您的故事板中,添加UIView,将其类更改为CircleView然后按住Ctrl键拖动以创建@IBOutlet。 Xcode会自动将其设置为@IBOutlet weak var circle: CircleView!,您可以设置其颜色(不要忘记删除var circle = CricleView()行。)