首页 > 解决方案 > Swift Playgrounds UIButton 无法正常工作

问题描述

我在 swift 操场上有这个 UIButton 称为“开始按钮”。这是它的设置。

    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)

我在 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
    }

但是当我点击一个按钮时,它不会运行名为“startButtonTapped”的函数,它只会将“Hello”打印到控制台。

这是函数'startButtonTapped'。

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

为什么当我点击按钮时它什么也不做?我怎样才能解决这个问题?
谢谢

标签: iosswiftuibutton

解决方案


我看不到你的其余代码。我只是快速创建了一个,以便您可以与自己的代码进行比较。

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

在此处输入图像描述


推荐阅读