john doe
john doe

Reputation: 9662

BezierPath in Swift Using Playgrounds

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))

Upvotes: 8

Views: 2956

Answers (2)

will
will

Reputation: 106

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

Upvotes: 2

Eric Aya
Eric Aya

Reputation: 70113

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. ;)

Upvotes: 11

Related Questions