如何让这个 UIButton 的 action 正确运行?

How to make this UIButton's action operate correctly?

每次我 运行 这个 swift 游乐场(在 Xcode 上),我在最后一行得到一个错误:

'PlaygroundView' 无法构造,因为它没有可访问的初始化程序。

我在第 4 行还有另一个错误:

class 'PlaygroundView' 没有初始值设定项。

import UIKit
import PlaygroundSupport

class PlaygroundView:UIViewController {

var introImage:UIImageView
var introButton:UIButton

override func loadView() {

    print("workspace started running.")

    //Main Constant and Variable Declarations/General Setup

    let mainView = UIView()

    //Main View Modifications & styling

    mainView.backgroundColor = UIColor.init(colorLiteralRed: 250, green: 250, blue: 250, alpha: 1)

    func addItem(item: UIView) {

        mainView.addSubview(item)

    }

    //Sub-Element Constant and Variable Declarations

    introImage = UIImageView(frame: CGRect(x: 87.5, y: -300, width: 200, height: 200))
    introImage.layer.borderColor = UIColor.black.cgColor
    introImage.layer.borderWidth = 4
    introImage.alpha = 0
    introImage.transform = CGAffineTransform(rotationAngle: -90.0 * 3.14/180.0)
    introImage.image = UIImage(named: "profile_pic.png")
    introImage.image?.accessibilityFrame = introImage.frame
    introImage.layer.cornerRadius = 100
    addItem(item: introImage)

    introButton = UIButton(frame: CGRect(x: 87.5, y: 900, width: 200, height: 30))
    introButton.alpha = 0
    introButton.setTitle("Tap to meet me", for: .normal)
    introButton.titleLabel?.font = UIFont(name: "Avenir Book", size: 20)
    introButton.backgroundColor = UIColor.black
    introButton.layer.cornerRadius = 15
    introButton.layer.borderWidth = 5

    addItem(item: introButton)

    introButton.addTarget(self, action: #selector(self.introButtonAction), for: .touchDown)

    UIView.animate(withDuration: 1.5, delay: 1, options: .curveEaseInOut, animations: {

        self.introImage.frame = CGRect(x: 87.5, y: 175, width: 200, height: 200)
        self.introButton.frame = CGRect(x: 87.5, y: 400, width: 200, height: 30)

        self.introImage.transform = CGAffineTransform(rotationAngle: 0.0 * 3.14/180.0)

        self.introImage.alpha = 1
        self.introButton.alpha = 1

    }) { (mainAnimationComped) in

        if mainAnimationComped == true {

            print("introduction animation comped.")

        }

    }


}

//User Interface Actions

func introButtonAction() {

    print("user interacted with user interface")

}

}

PlaygroundPage.current.liveView = PlaygroundView()

我该如何解决这个问题?

添加 ?在 introImage 和 introButton

之后
var introImage:UIImageView?
var introButton:UIButton?

那是因为在Swift中,您需要先初始化变量,然后才能在代码中使用它们。另一方面,因为在这种情况下你在你的函数中显式地设置它们,你可以将它们声明为隐式解包的可选值

var introImage:UIImageView!
var introButton:UIButton!

这应该可以在不更改代码中的任何其他内容的情况下工作