![](/img/trans.png)
[英]Pass String Variable Data from one Class/ViewController to Class/ViewController
[英]Pass data from ViewController to class
我对Swift还是很陌生,并且在这个问题上苦苦挣扎。 我想使用setSquareRec
将squareImage
的大小和点squareImage
到项目中的另一个swift文件中。
查看控制器:
class ViewController: UIViewController, SceneDelegate {
@IBOutlet var squareImage: UIImageView!
var scene = Scene()
func setSquareRec() {
scene.x = Int(squareImage.bounds.minX)
scene.y = Int(squareImage.bounds.minY)
scene.width = Int(squareImage.bounds.width)
scene.height = Int(squareImage.bounds.height)
}
...
}
班级:
protocol SceneDelegate{
func setSquareRec()
}
class Scene: SKScene {
var width = 0
var height = 0
var x = 0
var y = 0
...
let ARViewController = ViewController()
ARViewController.setSquareRec()
}
它给我一个错误Thread 5: Fatal error: Unexpectedly found nil while unwrapping an Optional value
在函数setSquareRec
的第一行scene.width = Int(sqareImage.bounds.minX)
)中Thread 5: Fatal error: Unexpectedly found nil while unwrapping an Optional value
, Thread 5: Fatal error: Unexpectedly found nil while unwrapping an Optional value
没有价值怎么可能?! 以及如何将其传递给另一个班级? 我看了这么多解决方案,但没有一个起作用,或者我不明白。
您可以通过let ARViewController = ViewController()
实例化视图控制器。
尝试从情节提要中对其进行充气。
随意询问是否不清楚。
实际上,您使用委托的方式是错误的,实际上您没有使用委托itselg。 请看下面的方法。
import UIKit
class ViewController: UIViewController, SceneDelegate {
@IBOutlet var squareImage: UIImageView!
var scene = Scene()
override func viewDidLoad() {
super.viewDidLoad()
//set delegate for scene as this delegate
scene.sceneDelegate = self
}
func setSquareRec() {
scene.x = Int(squareImage.bounds.minX)
scene.y = Int(squareImage.bounds.minY)
scene.width = Int(squareImage.bounds.width)
scene.height = Int(squareImage.bounds.height)
}
}
protocol SceneDelegate{
func setSquareRec()
}
class Scene: SKScene {
var width = 0
var height = 0
var x = 0
var y = 0
var sceneDelegate: SceneDelegate?
...
//call this delegate method like this
//This will call the setSquareRec method to any class who is set as delegate
sceneDelegate.setSquareRec()
...
}
未经测试的亲切测试,如有任何问题,请通知我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.