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

时间:2016-10-05 16:09:10

标签: ios swift uibutton swift-playground

我正在尝试在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)

1 个答案:

答案 0 :(得分:1)

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

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

  1. 定义一个Responser类。
  2. 将您要链接的动作写入此课程内的按钮
  3. 定义Responser的实例
  4. 将addTarget添加到实例并链接操作
  5. 代码示例

    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