snapchatdotcom snapchatdotcom - 10 months ago 57
Swift Question

Drawing the very first dot on a drawing app?

When I want to make a dot on the canvas, it doesn't appear. Even when I do a single touch, it's as if the program doesn't receive the first CGPoint value. Only when I move my finger do the point values appear (for example: (190.0, 375.5), (135, 234), ...)


class DV: UIView {
var lines: [Line] = []
var firstPoint: CGPoint!
var lastPoint: CGPoint!

required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)!

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastPoint = touches.first!.locationInView(self)
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
var newPoint = touches.first!.locationInView(self)

lines.append(Line(start: lastPoint, end: newPoint))
lastPoint = newPoint

override func drawRect(rect: CGRect) {
var context = UIGraphicsGetCurrentContext()
// print("fine") starts at beginning only

for line in lines {

CGContextMoveToPoint(context,line.start.x , line.start.y)
CGContextAddLineToPoint(context, line.end.x, line.end.y)

CGContextSetRGBFillColor(context, 0, 0, 0, 1)
CGContextSetLineCap(context, .Round)
CGContextSetLineWidth(context, 5)

Line.swift // My line initializer

class Line {
var start: CGPoint
var end: CGPoint

init(start _start: CGPoint, end _end: CGPoint) {
start = _start
end = _end


You are only using touchesBegan and touchesMoved, not touchesEnded, so if the touch doesn't move and then ends you are basically ignoring it. You need to implement touchesEnded to commit the drawing changes and draw them.