How to add a UIButton to Swift Playground? - swift

So I opened up playground, I just want to add a simple UIButton (or a simple UIView) for testing purposes. I can't get it to display though. 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'm doing wrong? Thanks

I think you can add button into playground and your code is correct you can see your button here when you click on Quick Look:
or you can see that button with clicking on Value History:
you dont need to add that into view.

If you import XCPlayground in your playground you can show views using:
let view=UIView()
//other setup
XCPShowView("View Title",view)
This will show the view in the assistant editor
To show the assistant editor goto View > Assistant Editor > Show Assistant Editor

import XCPlayground has been deprecated and is now import PlaygroundSupport.
You need to create your view first and give it a size.
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.black
then add PlaygroundPage.current.liveView = view to be able to see the view in the assistant editor.
now that you have created your view, and you can see the live preview of it. You can now add other views to it. In my playground I added several views so I created simple function with a 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)
Now there is a blue square in the center of my view.

I was just doing my sorting programming and pated the code..it will help you to add a button in playgroud with target.
import UIKit
import PlaygroundSupport
let aButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
aButton.backgroundColor = .lightGray
aButton.setTitle("Run Sorting", for: .normal)
aButton.layer.cornerRadius = 10
aButton.clipsToBounds = true
class Sorting {
#objc func callSorting() {
self.getSortedArrayUsingSelectionSort()
}
func getSortedArrayUsingSelectionSort() {
var arr = [4, 9, 10, 6, 1, 3]
let n = arr.count
for i in 0..<(n - 1) {
var minIndex = i
for j in (i+1)..<n {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
if minIndex != i {
let temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
} }
print(arr)
}
}
let target = Sorting()
aButton.addTarget(target, action: #selector(Sorting.callSorting), for: .touchUpInside)
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
containerView.backgroundColor = .white
PlaygroundPage.current.liveView = containerView
containerView.addSubview(aButton)

Related

Cannot find 'view' in scope swift 5

I understand that this is newbie question but I can not find answer on stackoverflow or google.
I created swift file with a function which access/call in every controller.
func showActivityIndicator(show: Bool) {
var activityIndicator : NVActivityIndicatorView!
let xAxis = view.center.x // or use (view.frame.size.width / 2) //error
let yAxis = view.center.y // or use (view.frame.size.height / 2)//error
let size = CGRect(x: (xAxis - 50), y: (yAxis - 50), width: 45, height: 45)
activityIndicator = NVActivityIndicatorView(frame: size)
activityIndicator.type = .ballSpinFadeLoader // add your type
activityIndicator.color = UIColor.red // add your color
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
but it gives me Cannot find 'view' in scope error.Thank you in advance!
You could create an extension. You can do that like this:
extension UIViewController {
func showActivityIndicator(show: Bool) {
var activityIndicator : NVActivityIndicatorView!
let xAxis = view.center.x // or use (view.frame.size.width / 2) //error
let yAxis = view.center.y // or use (view.frame.size.height / 2)//error
let size = CGRect(x: (xAxis - 50), y: (yAxis - 50), width: 45, height: 45)
activityIndicator = NVActivityIndicatorView(frame: size)
activityIndicator.type = .ballSpinFadeLoader // add your type
activityIndicator.color = UIColor.red // add your color
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
}
It works if you place your function in a class derived from UIViewController or as suggested you add extension to the class. I tested your function on my application and there were no problems with "view.center.x".

issue with animation in swift playground

I'm totally new to animations with swift and I started this concept by using playground here's my code below I have no "idea" why it doesn't work.
import UIKit
import PlaygroundSupport
let liveViewFrame = CGRect(x: 0, y: 0, width: 500, height: 500)
let liveView = UIView(frame: liveViewFrame)
liveView.backgroundColor = .white
PlaygroundPage.current.liveView = liveView
let smallFrame = CGRect(x: 0, y: 0, width: 100, height: 100)
let square = UIView(frame: smallFrame)
square.backgroundColor = .purple
liveView.addSubview(square)
UIView.animate(withDuration: 3.0) {
liveView.backgroundColor = .blue
}
This piece of code is working fine

I want to add subview inide the swift playgounds liveview for testing constraint but fail to display , the inner view added was disappeared

I want to add subview inide the swift playgounds liveview for testing constraint but fail to display , the inner view added was disappeared. it just draw in the quick look , but disappeared inside the liveview, how can i modify the position of the inner view with constaints ?
//: Playground - noun: a place where people can play
import UIKit
//import KeyBoardWubi
import PlaygroundSupport
var str = "Hello, playground"
var u1 : UIView
//u1 = KeyBoardWubi3(frame: CGRect(x: 20, y: 20, width: 200, height: 200))
//u1
var v1,v2,v3 : UIView
func addview(vin:UIView){
var v4 : UIView
v4 = UIView(frame : CGRect(x: 40, y: 40, width: 800, height: 100))
v4.backgroundColor = UIColor.blue
vin.addSubview(v4)
v4.translatesAutoresizingMaskIntoConstraints = false
v4.leftAnchor.constraint(equalTo: vin.leftAnchor, constant: 12.0).isActive = true
}
v1 = UIView(frame : CGRect(x: 0, y: 20, width: 200, height: 200))
v1.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = v1
addview(vin: v1)
v1
Your auto-layout constraint is invalid. It only has the left anchor. Playground does not warn you about invalid constraints. If this were a real app, you'd have known.
Try this:
import UIKit
import PlaygroundSupport
func addview(vin:UIView){
// Since you are using auto-layout, the initial frame is irrelevant
let v4 = UIView(frame: .zero)
v4.backgroundColor = .blue
// Set this **before** adding v4 to another view
v4.translatesAutoresizingMaskIntoConstraints = false
vin.addSubview(v4)
// Playground doesn't warn you about invalid auto layout constraints
// This is where you set the size and position of the new view
v4.leftAnchor.constraint(equalTo: vin.leftAnchor, constant: 40).isActive = true
v4.topAnchor.constraint(equalTo: vin.topAnchor, constant: 40).isActive = true
v4.widthAnchor.constraint(equalToConstant: 800).isActive = true
v4.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
let v1 = UIView(frame : CGRect(x: 0, y: 20, width: 200, height: 200))
v1.backgroundColor = UIColor.red
addview(vin: v1)
PlaygroundPage.current.liveView = v1

unable to find view with tag

In my viewWillAppear() I create a label and give it a tag. When another condition is met, I try to remove the label, but for some reason, that is not working and the label is still in the view. I must be doing something wrong...
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var label: UILabel?
// Add label if there are no recipes
if (recipeBook.recipesArr.count == 0) {
label = self.view.viewWithTag(123) as? UILabel
//label?.tag = 123 // arbitrary num
label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100))
label?.text = "Add A Recipe"
label?.textColor = UIColor(red:0.93, green:0.92, blue:0.92, alpha:1.0)
label?.font = label?.font.withSize(36)
label?.textAlignment = .center
self.view.addSubview(label!)
}
else {
// remove it
if let foundLabel = self.view.viewWithTag(123) {
foundLabel.removeFromSuperview()
} else {
print("Couldn't find label with tag in view")
}
}
}
I didn't realize in this line label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100)) I was creating a new label which has a default tag of 0. Changed it to label?.frame = CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100) so that I'm not creating a new label and everything is working fine. Silly mistake.
Your code is not doing what you think it is. If your recipesArr is empty (or more accurately the count is zero) you are trying to find a label/view with the tag 123. That is then ignored and you create a new label but don't give it a tag.
What you need to do is assign the label you create the tag 123 after you create it like this:
label?.tag = 123
Then you will have created the label and set it's tag so it can then subsequently be found.
you are recreating the label after the line label = UILabel(frame: CGRect
you can create the label programmatically like so without optionals:
lazy var recipeLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100))
label.tag = 123
label.text = "Add A Recipe"
label.font = UIFont.systemFont(ofSize: 17.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
then add it to your subview with iOS 9+ constraints if needed:
self.view.addSubview(recipeLabel)
then you can access the view anywhere by simply referencing the view recipeLabel or by the .tag property if you desire.

How to make this UIButton's action operate correctly?

Every time I run this swift playground (on Xcode), I get an error on the last line saying:
'PlaygroundView' cannot be constructed because it has no accessible initialisers.
I also have another error on line 4 saying:
class 'PlaygroundView' has no initializers.
import UIKit
import PlaygroundSupport
class PlaygroundView:UIViewController {
var introImage:UIImageView
var introButton:UIButton
override func loadView() {
print("workspace started running.")
//Main Constant and Variable Declarations/General Setup
let mainView = UIView()
//Main View Modifications & styling
mainView.backgroundColor = UIColor.init(colorLiteralRed: 250, green: 250, blue: 250, alpha: 1)
func addItem(item: UIView) {
mainView.addSubview(item)
}
//Sub-Element Constant and Variable Declarations
introImage = UIImageView(frame: CGRect(x: 87.5, y: -300, width: 200, height: 200))
introImage.layer.borderColor = UIColor.black.cgColor
introImage.layer.borderWidth = 4
introImage.alpha = 0
introImage.transform = CGAffineTransform(rotationAngle: -90.0 * 3.14/180.0)
introImage.image = UIImage(named: "profile_pic.png")
introImage.image?.accessibilityFrame = introImage.frame
introImage.layer.cornerRadius = 100
addItem(item: introImage)
introButton = UIButton(frame: CGRect(x: 87.5, y: 900, width: 200, height: 30))
introButton.alpha = 0
introButton.setTitle("Tap to meet me", for: .normal)
introButton.titleLabel?.font = UIFont(name: "Avenir Book", size: 20)
introButton.backgroundColor = UIColor.black
introButton.layer.cornerRadius = 15
introButton.layer.borderWidth = 5
addItem(item: introButton)
introButton.addTarget(self, action: #selector(self.introButtonAction), for: .touchDown)
UIView.animate(withDuration: 1.5, delay: 1, options: .curveEaseInOut, animations: {
self.introImage.frame = CGRect(x: 87.5, y: 175, width: 200, height: 200)
self.introButton.frame = CGRect(x: 87.5, y: 400, width: 200, height: 30)
self.introImage.transform = CGAffineTransform(rotationAngle: 0.0 * 3.14/180.0)
self.introImage.alpha = 1
self.introButton.alpha = 1
}) { (mainAnimationComped) in
if mainAnimationComped == true {
print("introduction animation comped.")
}
}
}
//User Interface Actions
func introButtonAction() {
print("user interacted with user interface")
}
}
PlaygroundPage.current.liveView = PlaygroundView()
How would I fix this problem?
That's because in Swift, you need to initialize variables before use them in the code. On the other hand, since in this case you set them explicitly in your function, you might declare them as implicitly unwrapped optionals
var introImage:UIImageView!
var introButton:UIButton!
and this should work without changing anything else in your code
Add ? after introImage and introButton
var introImage:UIImageView?
var introButton:UIButton?