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

心已入冬 提交于 2019-12-08 03:30:28

问题


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)

回答1:


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


来源:https://stackoverflow.com/questions/39878959/how-to-get-a-uibutton-to-perform-action-in-a-swift-playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!