0

I came across an example in a book for learning iOS 13 programming.The example intends to draw an arrow like the one in the following picture:

enter image description here

The code for the example is as follows:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        drawArrow()
    }

    func drawArrow () {
        // obtain the current graphics context
        guard let con = UIGraphicsGetCurrentContext() else { return }
        // draw a black (by default) vertical line, the shaft of the arrow
        con.move(to: CGPoint(100, 100))
        con.addLine(to: CGPoint(100, 19))
        con.setLineWidth(20)
        con.strokePath()
        // draw a red triangle, the point of the arrow
        con.setFillColor(UIColor.red.cgColor)
        con.move(to: CGPoint(80, 25))
        con.addLine(to: CGPoint(120, 25))
        con.fillPath()
        // snap a triangle out of the shaft by drawing in Clear blend mode
        con.move(to: CGPoint(90, 101))
        con.addLine(to: CGPoint(100, 90))
        con.addLine(to: CGPoint(110, 101))
        con.setBlendMode(.clear)
        con.fillPath()
    }
}

However, when run, the line of code guard let con = UIGraphicsGetCurrentContext() else { return } failed to produce the CGContext instance as expected. I'm not sure why it is like that. Would you please help explain why and suggest a solution to the issue? Thank you very much!

1 Answer 1

2

That's my book and my arrow and you didn't follow the directions in the book. The example tells you to be in a UIView subclass and that this code should be called from your draw(_:) override.

2
  • 1
    See github.com/mattneub/Programming-iOS-Book-Examples/blob/… for working examples of this and all the code in the book
    – matt
    Commented Jun 18, 2021 at 22:20
  • Thank you very much, @matt, for your immediate help! I'm surprised and happy to get the answer from the author of the book himself! I'm sorry that I only focused on the code snippet in the book and forgot to consult the full-code examples provided by you. Turned pages too fast when reading the Preface :). Thanks again for your help! Commented Jun 18, 2021 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.