How to add UIButton to Swift Playground?

So I opened a playground, I just want to add a simple UIButton (or a simple UIView) for testing. Although I cannot display it. This is what I have so far:

import UIKit

var uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
uiButton.frame  = CGRectMake(0, 0, 100, 100)
uiButton.setTitle("Test", forState: UIControlState.Normal);
//self.view.addSubview(uiButton) <-- doesn't work

      

Do you guys know what I am doing wrong? Thanks to

+3


source to share


3 answers


I think you can add a button to the playground and your code is correct, you can see your button here when you click the Quick Look:

enter image description here

or you can see this button by clicking on "History of values":



enter image description here

you don't need to add this to the view.

+5


source


If you are import XCPlayground

in a playground, you can render views using:

let view=UIView()
//other setup
XCPShowView("View Title",view)

      



This will show the view in the editor assistant

To show the goto editor helper View > Assistant Editor > Show Assistant Editor

+2


source


import XCPlayground

deprecated now import PlaygroundSupport

. First you need to create your own view and size it.

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) view.backgroundColor = UIColor.black

then add PlaygroundPage.current.liveView = view

to see the view in the helper editor.

now that you have created your view and you can preview it. Now you can add other views to it. In my playground, I added a few views, so I created a simple function with default width and height.

func addSquareView(x: Int, y: Int, width: Int = 100, height: Int = 100, color: UIColor) { let newView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) newView.backgroundColor = color view.addSubview(newView) }

addSquareView(x: 100, y: 100, color: .blue)

There is now a blue square in the center of my gaze.

0


source







All Articles