如何让UIButton在Swift Playground中执行操作

问题描述 投票:2回答:1

我想在Swift Playground应用程序中使用UIKit。我可以让标签和文本字段工作,但我无法弄清楚如何让UIButton在触摸时执行操作。

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)
ios swift uibutton swift-playground
1个回答
1
投票

您的代码稍作修改,对我有用。

对于遇到同样问题的人,建议:

  1. 定义一个Responser类。
  2. 编写要链接到此类内部按钮的操作
  3. 定义Response的实例
  4. addTarget到实例并链接动作

代码示例

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
© www.soinside.com 2019 - 2024. All rights reserved.