简体   繁体   English

如何从不同的swift文件访问一个类中的所有对象

[英]How to access all objects in one class from a different swift file

I'm trying to change the properties of a few IBOutlets from a different swift file and class. 我正在尝试从不同的swift文件和类更改一些IBOutlet的属性。 Ex: run function in class B (type UIView) to alter the alpha of IBOutlet in class A (type UIViewController). 例如:运行类B(类型UIView)中的函数以更改类A(类型UIViewController)中IBOutlet的alpha。 I've tried many different ways of accessing them (extensions,superclasses) but I still get nil values for these outlets. 我尝试了多种不同的访问方式(扩展名,超类),但对于这些出口,我仍然获得nil值。 I am aware that this is because the view is allocated for but not loaded, but I cannot find a way to store and access class "A"'s outlets correctly to avoid this. 我知道这是因为视图是为分配但未加载的,但是我无法找到正确存储和访问类“ A”的插座的方法来避免这种情况。 Here is my code from class "B" : 这是我的“ B”类代码:

 let mainView = MainViewController()  //Code in B
  var changeAlpha = mainView.changeText() //Code in B

func changeAlpha() {               //Code in class MainViewController
    self.hotLabel.alpha = 0
}

Thanks in advance! 提前致谢!

Don't try to allocate the MainViewController again. 不要尝试再次分配MainViewController

Try to access the existing MainViewController instead. 尝试改为访问现有的MainViewController

var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.nextResponder()
            if let mainView = parentResponder as? MainViewController {
                var changeAlpha = mainView.changeText()
            }
        }

When you try to create an object of MainViewController class (which is already includes your data), the values that you have stored earlier will not be accessible because the reference will be different for these two class objects 当您尝试创建MainViewController类的对象(已经包含您的数据)时,您先前存储的值将无法访问,因为这两个类对象的引用将不同

You have to pass the existing MainViewController class into the B class or try to access the existing MainViewController or implement the messaging concepts. 您必须将现有的MainViewController类传递给B类,或者尝试访问现有的MainViewController或实现消息传递概念。

The only way to solve these kind of issues is, try to study the OOPS basic concepts (especially object life cycle, allocation etc..) before writing the code. 解决此类问题的唯一方法是,在编写代码之前,尝试研究OOPS基本概念(尤其是对象生命周期,分配等)。

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

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