如何让 UIButton 在 Swift Playground 中执行操作 [英] How to get a UIButton to perform action in a Swift Playground

查看:30
本文介绍了如何让 UIButton 在 Swift Playground 中执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Swift Playground 应用中使用 UIKit.我可以让标签和文本字段工作,但我不知道如何让 UIButton 在被触摸时执行操作.

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)

推荐答案

对您的代码进行了少量更改,它对我有用.

Minor change of your code and it worked for me.

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

For anyone who meet the same problem, suggestion:

  1. 定义一个响应者类.
  2. 在该类中编写要链接到按钮的操作
  3. 定义一个 Responser 实例
  4. 将目标添加到实例并链接操作

代码示例

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

这篇关于如何让 UIButton 在 Swift Playground 中执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆