简体   繁体   English

从其他类Swift访问UI对象的属性

[英]Access UI object's properties from other class Swift

I have this class in Swift 2.0: 我在Swift 2.0中有此类:

class CharacterSelectionController: UIViewController {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var scnView: SCNView!

    var characterArray = [CharacterInfo]()
    var scene: CharacterScene!

    override func viewDidLoad() {

        // Set up the SCNView
        scnView.backgroundColor = AppDelegate().lightBlueColor()
        scnView.showsStatistics = false
        scnView.antialiasingMode = SCNAntialiasingMode.Multisampling2X
        scnView.overlaySKScene = SKScene(size: view.bounds.size)
        scnView.playing = false

       // Start playing the scene
      scnView.scene = scene
      scnView.scene!.rootNode.hidden = false
      scnView.play(self)

In the AppDelegate and other classes I have to set scnView to pause, something like scnView.pause(self). 在AppDelegate和其他类中,我必须将scnView设置为暂停,例如scnView.pause(self)。 However I cannot seem to be able to access either the view or the self part in the other class. 但是,我似乎无法访问其他类中的视图或自身部分。 I tried setting some struct in this way: 我试图以这种方式设置一些结构:

struct GlobalVariables {
    static var globalGameView: SCNView = SCNView()
}

and then setting globalGameView = scnView but It doesn't work. 然后设置globalGameView = scnView,但是它不起作用。 I also tried: 我也尝试过:

    var myCustomViewController: CharacterSelectionController = CharacterSelectionController(nibName: nil, bundle: nil)
    myCustomViewController.scnView.pause(myCustomViewController)
    print(myCustomViewController.scnView)

but the app crashes... Any ideas? 但是应用程序崩溃了...有什么想法吗?

You should not try to access another view controller's view objects. 您不应尝试访问另一个视图控制器的视图对象。 That is a violation of the encapsulation principle of object-oriented design. 这违反了面向对象设计的封装原理。 Treat another view controller's views as private. 将另一个视图控制器的视图视为私有。

What you should do is to add a public method to the other view controller that does the changes for you, and the call that method. 您应该做的是向另一个为您进行更改的视图控制器中添加一个公共方法,然后调用该方法。 That way, if you decide to switch your view controller to draw its contents using Metal instead of SceneKit at some future date, you can do that and only your one view controller has to change. 这样,如果您决定在将来某个日期切换视图控制器以使用Metal而不是SceneKit绘制其内容,则可以执行此操作,只需更改一个视图控制器即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM