如何使这个 UIButton 的动作正确运行?
Posted
技术标签:
【中文标题】如何使这个 UIButton 的动作正确运行?【英文标题】:How to make this UIButton's action operate correctly? 【发布时间】:2017-03-24 23:11:10 【问题描述】:每次我(在 Xcode 上)运行这个 swift playground 时,最后一行都会出现错误:
'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()
我该如何解决这个问题?
【问题讨论】:
【参考方案1】:那是因为在 Swift 中,您需要先初始化变量,然后才能在代码中使用它们。另一方面,由于在这种情况下您在函数中显式设置它们,您可以将它们声明为隐式展开的可选项
var introImage:UIImageView!
var introButton:UIButton!
这应该可以在不更改代码中的任何其他内容的情况下工作
【讨论】:
【参考方案2】:添加?在 introImage 和 introButton 之后
var introImage:UIImageView?
var introButton:UIButton?
【讨论】:
谢谢!我完全按照你说的做了,而且奏效了。还有这个网站:ralfebert.de/snippets/ios/uikit-playground/UIButton 帮助我完成了我的项目。以上是关于如何使这个 UIButton 的动作正确运行?的主要内容,如果未能解决你的问题,请参考以下文章