Swift游乐场UIButton无法正常工作

问题描述 投票:0回答:1

我在快速游乐场里有这个名为“开始按钮”的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")
    }

点击按钮时为什么不做任何事情?我怎样才能解决这个问题? 谢谢

ios swift uibutton
1个回答
0
投票

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

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.