在iPad上的Playground应用程序中创建一个按钮

时间:2016-07-02 03:30:16

标签: ios swift-playground

我正在使用iOS 10中Playground应用的新测试版。 我想让一些UIKit元素在操场上工作。 Swift 3和Swift 2差别不大,我遇到了一些问题。

我有一个标签和文本框工作,但我无法按钮工作。 我有按钮显示但无法获取文本或触摸操作的动作。 这是我的代码。

import PlaygroundSupport
import UIKit

//
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.909803926944733, green: 0.47843137383461, blue: 0.643137276172638, alpha: 1.0)
PlaygroundPage.current.liveView = view

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.borderStyle = UITextBorderStyle.roundedRect
view.addSubview(txt)

func buttonPressed(sender: UIButton)
{
    //sender.backgroundColor = #colorLiteral(red: 0.725490212440491, green: 0.47843137383461, blue: 0.0980392172932625, alpha: 1.0)
}

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.focused)
button.setTitle("button", for: UIControlState.focused)
button.layer.cornerRadius = 10
button.addTarget(button, action: "buttonPressed", for:  UIControlEvents.touchUpInside)
view.addSubview(button)

1 个答案:

答案 0 :(得分:5)

我一直在尝试相同,以下代码适用于我:

import UIKit
import PlaygroundSupport

class Receiver {
    @objc func buttonClicked() {
        print("click")
    }
}

let view = UIView()
view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let receiver = Receiver()
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 50))
button.setTitle("TestButton", for: .normal)
button.setTitleColor(#colorLiteral(red: 0.474509805440903, green: 0.839215695858002, blue: 0.976470589637756, alpha: 1.0), for: .normal)
button.addTarget(receiver, action: #selector(Receiver.buttonClicked), for: .touchUpInside)
PlaygroundPage.current.liveView = view
view.addSubview(button)

我认为重要的区别在于您将按钮添加为.touchUpInside事件的目标。不幸的是,该按钮没有实现您的buttonPressed方法(它只是在Playground中定义,而不是作为UIButton类的一部分)。由于一般操场中没有self(用于引用您编写的函数),我将其包装到一个新类中,并使用此类的实例作为.touchUpInside事件的接收者。