-1

Old programmer here teaching myself a bit of macOS and iOS programming. I thought the Swift Playgrounds app might be a way to experiment with some simple pixel drawing code.

But Googling and browsing the net are letting me down. Even the chatbots only give code that Playgrounds rejects.

In Playgrounds is there AppKit, UIKit, NSView, UIView, CoreGraphics, or some special equivalent peculiar to Playgrounds?

The Playgrounds examples seem to go straight to more complex more modern graphics that look more like sprites and GL than the simple stuff I want to try.

hippietrail
  • 15,848
  • 18
  • 99
  • 158

1 Answers1

0

Yes! After hours of experimenting and searching I stumbled across this answer by HangarRash on a question that wasn't even about Playgrounds. Here's a simplified/minimal snippet:

import UIKit
import PlaygroundSupport

class CustomView: UIView {
    var r: CGFloat = 25
    var c: UIColor = .blue

    override func draw(_ rect: CGRect) {
        let p = UIBezierPath()
        p.move(to: CGPoint(x: w/3, y: h/3))
        p.addLine(to: CGPoint(x: w*2/3-1, y: h/3))
        p.addLine(to: CGPoint(x: w*2/3-1, y: h*2/3-1))
        p.addLine(to: CGPoint(x: w/3, y: h*2/3-1))
        p.close()
        self.c.setFill()
        p.fill()
    }
}

let v = CustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 150))
v.backgroundColor = .clear
v.fillColor = .blue
PlaygroundPage.current.liveView = v

It seems the key concepts would seem to be PlaygroundSupport and PlaygroundPage.current.liveView.

hippietrail
  • 15,848
  • 18
  • 99
  • 158