简体   繁体   English

Swift Playgrounds UIButton无法正常工作

[英]Swift playgrounds UIButton not working correctly

I've got this UIButton called 'start button' in swift playgrounds. 我在迅速的操场上有了一个名为“开始按钮”的UIButton。 This is the setup for it. 这是它的设置。

    func setupStartButton() {
        startButton.frame = CGRect(x: 15, y: 550, width: 125, height: 50)
        startButton.backgroundColor = UIColor(ciColor: CIColor(red: 255/255, green: 0/255, blue: 77/255, alpha: 1.0))
        startButton.layer.cornerRadius = 20
        startButton.setTitle("Start", for: .normal)
        startButton.setTitleColor(.white, for: .normal)
        startButton.addTarget(self, action: #selector(startButtonTapped), for: .touchUpInside)
        view.addSubview(startButton)

I call this in viewDidLoad(). 我在viewDidLoad()中称呼它。

    override func viewDidLoad() {
        view.frame = CGRect(x: 0, y: 0, width: 524, height: 766)
        view.backgroundColor = .white

        setupStartButton()

        PlaygroundPage.current.liveView = view
        PlaygroundPage.current.needsIndefiniteExecution = true
    }

But when I tap on a button it doesn't run the function called 'startButtonTapped' which just prints "Hello" to the console. 但是,当我点击一个按钮时,它不会运行名为“ startButtonTapped”的功能,该功能只会在控制台上显示“ Hello”。

This is the function 'startButtonTapped'. 这是功能“ startButtonTapped”。

    @objc func startButtonTapped() {
        print("Hello")
    }

Why does it not do anything when I tap the button? 为什么当我点击按钮时它什么都不做? How can I fix this? 我怎样才能解决这个问题?
Thank you 谢谢

I can't see the rest of your code. 我看不到其余的代码。 I just quickly created one so that you could compare with your own code. 我刚刚快速创建了一个,以便您可以与自己的代码进行比较。

import UIKit
import PlaygroundSupport

class VC: UIViewController {

    let startButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()

        setupStartButton()
    }

    func setupStartButton() {
        startButton.frame = CGRect(x: 15, y: 550, width: 125, height: 50)
        startButton.backgroundColor = UIColor(ciColor: CIColor(red: 255/255, green: 0/255, blue: 77/255, alpha: 1.0))
        startButton.layer.cornerRadius = 20
        startButton.setTitle("Start", for: .normal)
        startButton.setTitleColor(.white, for: .normal)
        startButton.addTarget(self, action: #selector(startButtonTapped), for: .touchUpInside)
        view.addSubview(startButton)
    }

    @objc func startButtonTapped() {
        print("Hello")
    }
}

let vc = VC()
PlaygroundPage.current.liveView = vc

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM