【问题标题】:Swift playgrounds UIButton not working correctlySwift Playgrounds UIButton 无法正常工作
【发布时间】:2019-03-13 22:55:12
【问题描述】:

我在 Swift Playground 中有一个名为“开始按钮”的 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")
    }

为什么当我点击按钮时它什么也不做? 我该如何解决这个问题?
谢谢

【问题讨论】:

  • 它打印到控制台而不是屏幕。
  • 我知道,但它没有打印到控制台
  • 显示更多代码,以便人们可以重复这种情况。我尝试使用空白模板并添加您当前的代码。一切都很好
  • 您可以尝试将您的 startButtonTapped 更改为 startButtonTapped(_ sender: UIButton)。也别忘了在startButton.addTarget(self, action: #selector(startButtonTapped), for: .touchUpInside) 中更改它
  • 不,还是不行,我很困惑。

标签: ios swift uibutton


【解决方案1】:

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

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

【讨论】:

  • 是的,它现在可以工作了,在我没有将视图控制器类保存到变量然后将其分配给实时视图之前。谢谢
猜你喜欢
  • 2021-09-25
  • 2018-09-09
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
相关资源
最近更新 更多