【发布时间】:2019-10-27 19:45:15
【问题描述】:
当调用 View Controller 类中的 func dizzy 时,我的代码试图将线条的颜色从红色更改为蓝色。问题是我不知道如何从类视图控制器中做到这一点。我可以在 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()
}
}
【问题讨论】:
标签: swift uiview subclass cgpoint uigraphicscontext