8

Do I have to create a custom class in order to use the BezierPath in the Swift playgrounds?

The following code displays nothing but black background:

import UIKit
import XCPlayground

class GraphView : UIView {

    override func drawRect(rect: CGRect) {

        let path = UIBezierPath(rect: rect)
        path.moveToPoint(CGPointMake(0,0))
        path.addLineToPoint(CGPointMake(50,100))
        path.closePath()
        UIColor.redColor().setFill()

        path.stroke()
    }

}


let graphView = GraphView(frame: CGRectMake(0,0,960,640))
john doe
  • 9,220
  • 23
  • 91
  • 167
  • Set the view backgroundColor to white and you'll see your line. It's black, though, not red. See http://stackoverflow.com/a/34659468/2227743 for fabulous tips. – Eric Aya May 02 '16 at 18:47
  • I am using Playgrounds! – john doe May 02 '16 at 18:49
  • Yes, I know you are using Playgrounds. Look at my answer. – Eric Aya May 02 '16 at 18:50
  • 3
    FYI, you set the fill color, but then only `stroke`. If you wanted to stoke, call `UIColor.redColor().setStroke()`. If you want to fill with `UIColor.redColor().setFill()`, call `fill`, not `stroke`. – Rob May 02 '16 at 20:44

2 Answers2

11

You have to use this at the end of your code:

XCPlaygroundPage.currentPage.liveView = graphView

and to open the Playground's "Assistant Editor" to see the result.

And also to change the background color of the view since it's black... and your line is also black. ;)

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • I got it working but the left hand side Assistant Editor simply says "GraphView" it does not show the graph or the rendered output – john doe May 02 '16 at 18:56
  • [Screenshot of my Playground](https://www.evernote.com/l/AFnk7PAzYtBNIKHvk2LITLvkUQg4x261xz4) with the assistant panel on the right. – Eric Aya May 02 '16 at 18:59
  • 2
    Swift 3+: `PlaygroundPage.current.liveView = graphView` – Grubas May 22 '18 at 14:26
2

In Swift 5:

import UIKit

class GraphView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        let path = UIBezierPath(rect: rect)
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 50, y: 100))
        path.stroke()
    }

}

let graphView = GraphView(frame: CGRect(x: 0, y: 0, width: 960, height: 640))

screenshot of view in playground Swift 5.2, Xcode 11.4

willtherussian
  • 106
  • 1
  • 4