My code is trying to call a class which controlls all the drawing properties and nothing is showing up on the uiview. It's like the class is not being called but I know its being called. I don't know what to do. It is important that canvas covers a specific area and not the entire view thats why I programmed constraint it.
var canvas = Canvas()
override func viewDidLoad() {
super.viewDidLoad()
canvas.backgroundColor = .black
setupLayout()
canvas.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(canvas)
NSLayoutConstraint.activate ([
canvas.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
canvas.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 0),
canvas.widthAnchor.constraint(equalToConstant: 300),
canvas.heightAnchor.constraint(equalToConstant: 300),
])
}
class Canvas: UIView {
// public function
func undo() {
_ = lines.popLast()
setNeedsDisplay()
}
func clear() {
lines.removeAll()
setNeedsDisplay()
}
fileprivate 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: nil) else { return }
guard var lastLine = lines.popLast() else { return }
lastLine.append(point)
lines.append(lastLine)
setNeedsDisplay()
}}
Change the below line
guard let point = touches.first?.location(in: nil) else { return }
to this
guard let point = touches.first?.location(in: self) else { return }
The points stored in lines array are corresponding to the superview to which your CanvasView was attached to. You need to store the points corresponding to CanvasView. That's exactly what the self parameter does in place of nil above.