簡體   English   中英

將數據從ViewController傳遞給類

[英]Pass data from ViewController to class

我對Swift還是很陌生,並且在這個問題上苦苦掙扎。 我想使用setSquareRecsquareImage的大小和點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 valueThread 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM