Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BezierPath in Swift Using Playgrounds

Tags:

ios

swift

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))
like image 566
john doe Avatar asked May 02 '16 18:05

john doe


2 Answers

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

like image 145
Eric Aya Avatar answered Nov 16 '22 18:11

Eric Aya


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

like image 27
willtherussian Avatar answered Nov 16 '22 19:11

willtherussian