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
source to share
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.
source to share