Reputation: 21
I'm quite new to Swift and I'm struggling with this issue. I want to pass the size and point of squareImage
to a different swift file in my project using setSquareRec
.
View Controller:
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)
}
...
}
The class:
protocol SceneDelegate{
func setSquareRec()
}
class Scene: SKScene {
var width = 0
var height = 0
var x = 0
var y = 0
...
let ARViewController = ViewController()
ARViewController.setSquareRec()
}
It gives me the error Thread 5: Fatal error: Unexpectedly found nil while unwrapping an Optional value
in the first line ( scene.width = Int(sqareImage.bounds.minX)
) of the function setSquareRec
How is it possible that is has no value?! And how is it possible to pass it to another class? I looked at so many solutions but none of them worked or I don't get it.
Upvotes: 2
Views: 548
Reputation: 231
The way you are using your delegate is wrong infact you are not using the delegate itselg. Kindly look at the approach below.
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()
...
}
not tested kindly test let me know incase of any issue
Upvotes: 1
Reputation: 410
You instantiate your view controller with let ARViewController = ViewController()
.
Try inflating it from a storyboard.
Feel free to ask if it isn't clear.
Upvotes: 1