Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Swift playground to display NSView with some drawing?

Basically I would like to test a chart drawing in a Swift playground in NSView.

like image 211
Alfa07 Avatar asked Jun 04 '14 18:06

Alfa07


People also ask

Is Swift Playgrounds good for learning code?

Learning to code with Swift Playgrounds is incredibly engaging. The app comes with a complete set of Apple-designed lessons. Play your way through the basics in “Get Started with Code” using real code to guide a character through a 3D world. Then move on to more advanced concepts.

What can you do with Swift Playgrounds?

Swift Playgrounds -- which works on iPads or Macs -- starts out like a puzzle game where players have to figure out how to enter and test code until they find the right solution. The code they learn to use is in Apple's Swift language, which professional developers use to create iOS apps.


2 Answers

Here is what I am using now:

class CustomView: NSView {
  init(frame: NSRect) {
    super.init(frame: frame)
  }
  override func drawRect(dirtyRect: NSRect) {
    color.setFill()
    NSRectFill(self.bounds)
    NSColor.yellowColor().setFill()
    var r = NSMakeRect(0, y, self.bounds.width, 5)
    NSRectFill(r)
  }

  var color = NSColor.greenColor()
  var y: CGFloat = 0
}
var view = CustomView(frame:
  NSRect(x: 0, y: 0, width: 300, height: 300))

view.color = NSColor.greenColor()
XCPShowView("chart", view)

for var i = 0; i < 100; ++i {
  view.y = CGFloat(i) // <- try click on a plus sign opposite this line to add it to timeline
}
like image 142
Alfa07 Avatar answered Nov 16 '22 04:11

Alfa07


try this code in your xcode swift playground environment, be sure to put all object initialization in init, because draw gets executed multiple times :-), this is just a simple sample, more to come ...

import Cocoa
import XCPlayground


  class CustomView: NSView {
    init(frame: NSRect) {
        super.init(frame: frame)

        antibez.moveToPoint(NSPoint(x: 10 , y: 10))
        for i in 0..25
        {
            antibez.lineToPoint(NSPoint(x: 20 + 10 * (25-i), y: 20 + 10 * i))
            antibez.moveToPoint(NSPoint(x: 10 + 10 * (i), y: 10 ))

        }
    }
    override func drawRect(dirtyRect: NSRect) {
        color.setFill()
        NSRectFill(self.bounds)
        antibez.stroke()

    }

    var color = NSColor.greenColor()

    var antibez = NSBezierPath()
  }
  var view = CustomView(frame:
    NSRect(x: 0, y: 0, width: 300, height: 300))

  XCPShowView("chart", view)
like image 31
Ben Croughs Avatar answered Nov 16 '22 03:11

Ben Croughs