Mr. Coxall
Mr. Coxall

Reputation: 211

How to get a UIButton to perform action in a Swift Playground

I am trying to use UIKit in the Swift Playground app. I can get labels and text fields working, but I can not figure out how to get a UIButton to perform an action when it is touched.

import PlaygroundSupport
import UIKit

class MyView: UIView {

    //Method to be called
    func printname()
    {
        print ("clicked")
    }

    func buttonPressed(sender: UIButton)
    {
        print ("Here")
    }
}

func printname2()
{
   print("button pressed")
}

let view = MyView()
PlaygroundPage.current.liveView = view

let button = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 50))
button.addTarget(view, action: #selector(MyView.printname), for:        UIControlEvents.touchUpInside)
view.addSubview(button)

Upvotes: 2

Views: 3247

Answers (1)

xue
xue

Reputation: 2475

Minor change of your code and it worked for me.

For anyone who meet the same problem, suggestion:

  1. Define a Responser class.
  2. write the action you want to link to button inside this class
  3. define an instance of Responser
  4. addTarget to the instance and link the action

Code Example

import PlaygroundSupport
import UIKit

//
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.909803926944733, green: 0.47843137383461, blue: 0.643137276172638, alpha: 1.0)
view.frame = CGRect(x: 0, y: 0, width: 400, height: 300)


let lbl = UILabel(frame: CGRect(x: 50, y: 0, width: 200, height: 50))
lbl.text = "Hello, World!"
view.addSubview(lbl)

let txt = UITextField(frame: CGRect(x: 150, y: 200, width: 200, height: 50))
txt.placeholder = "Enter text here"
//txt.font = UIFont.systemFont(ofSize: 15)
txt.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
txt.borderStyle = UITextBorderStyle.roundedRect

view.addSubview(txt)

let button = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 50))
button.backgroundColor = #colorLiteral(red: 0.721568644046783, green: 0.886274516582489, blue: 0.592156887054443, alpha: 1.0)
//button.setTitleColor(#colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0), for: UIControlState.selected)
button.setTitle("button", for: UIControlState.selected)
button.layer.cornerRadius = 10
view.addSubview(button)

class Responser: NSObject
{

    //Method to be called
    func printname()
    {
        print ("clicked")
        lbl.text = "aha"
    }
}

let responder = Responser()
button.addTarget(responder, action: #selector(Responser.printname), for:.touchUpInside)

PlaygroundPage.current.liveView = view

Upvotes: 1

Related Questions