我的代码试图在类View Controller中调用func头晕时将线的颜色从红色更改为蓝色。问题是我不知道如何从类视图控制器做到这一点。我可以在Canvas类中做到这一点,但是我需要通过func晕眩来控制它,因为它充当viewController类中的按钮。我不在乎是否必须在canvas func中创建一个func然后从viewController中调用它。
class ViewController: UIViewController {
var canvas = Canvas()
@objc func dizzy() {
}}
class Canvas: UIView {
// public function
func undo() {
_ = lines.popLast()
setNeedsDisplay()
}
func clear() {
lines.removeAll()
setNeedsDisplay()
}
var lines = [[CGPoint]]()
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(5)
context.setLineCap(.butt)
lines.forEach { (line) in
for (i, p) in line.enumerated() {
if i == 0 {
context.move(to: p)
} else {
context.addLine(to: p)
}
}
}
context.strokePath()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
lines.append([CGPoint]())
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let point = touches.first?.location(in: self) else { return }
guard var lastLine = lines.popLast() else { return }
lastLine.append(point)
lines.append(lastLine)
setNeedsDisplay()
}
}
在strokeColor
中添加一个名为Canvas
的属性:
class Canvas : UIView {
var strokeColor = UIColor.red {
didSet {
self.setNeedsDisplay()
}
}
...
}
在strokeColor
中使用draw(rect:)
:
context.setStrokeColor(strokeColor.cgColor)
然后在dizzy()
中将画布的strokeColor
设置为.blue
:
class ViewController: UIViewController {
var canvas = Canvas()
@objc func dizzy() {
canvas.strokeColor = .blue
}
}
每次设置strokeColor
的Canvas
时,都会通过在其self.setNeedsDisplay()
属性观察器中调用didSet
来触发重绘。对draw(rect:)
的新调用将使用新颜色重绘视图。