gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:13:57 25 4
gpt4 key购买 nike

每次我运行这个 swift playground(在 Xcode 上)时,我都会在最后一行收到一个错误:

无法构造“PlaygroundView”,因为它没有可访问的初始化器。

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

“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()

我该如何解决这个问题?

最佳答案

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

var introImage:UIImageView!
var introButton:UIButton!

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

关于swift - 如何让这个 UIButton 的 action 正确运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43010582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com