如何从另一个类访问IBOutlet [英] How to access an IBOutlet from another class

查看:323
本文介绍了如何从另一个类访问IBOutlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何访问从另一个类中声明的类中的@IBOutlet

I want to know how to access an @IBOutlet declared in a class from another class

例如,我有一个名为myfirstview的类

for example, I have a class named myfirstview

class MyFirstView: UIViewController {

    @IBOutlet var lblred: UILabel! = UILabel()
}

我想更改<$ c $的文本c> lblred 来自另一个名为 MySecondView 的类,该类写在另一个 .swift 文件中:

I want to change the text of the lblred from another class named MySecondView which is written in another .swift file:

class MySecondView: UIViewController {

    func modify() {
        let mfv = MyFirstView()
        mfv.lblred.text = "Hello"
    }
}

但没有任何反应。

我用故事板标签连接了 lblred 。我在网上搜索过很多关于这个但我找不到可以解决我问题的那个。请帮我解决这个问题。

But nothing happens.
I have connected lblred with a storyboard label. I have searched a lot about this on the web but I can't find the one which can solve my problem. Please help me solve this problem.

谢谢。

推荐答案

@Sheen对你的直接问题是正确的,但你的问题更深入。没有对象应该访问另一个对象的IBOutlets。它没有明确定义会发生什么。这是ObjC代码中很长的错误来源,Swift将这些常见错误升级为崩溃。

@Sheen is correct about your immediate problem, but your problem is deeper. No object should access another object's IBOutlets. It's not well defined what will happen. This has been a long source of bugs in ObjC code, and Swift escalates those common bugs to crashes.

在加载视图之前,不会分配IBOutlets。这意味着如果视图控制器已分配但尚未放在屏幕上,则IBOutlets仍为零。访问隐式解包的nil会使Swift崩溃。

IBOutlets are not assigned until the view is loaded. This means that if the view controller is allocated but has not been put on the screen yet, the IBOutlets are still nil. Accessing an implicitly unwrapped nil will crash Swift.

视图控制器只应与其子视图控制器通信。它们不应与系统中的任意视图控制器通信。任意视图控制器之间的通信是通过模型完成的。一个视图控制器更新模型,另一个视图控制器从模型中读取。这是大多数Cocoa都是模型 - 视图 - 控制器模式。

View controllers should only communicate with their children view controllers. They should not communicate with arbitrary view controllers in the system. Communication between arbitrary view controllers is done via the model. One view controller updates the model, and another view controller reads from the model. This is the Model-View-Controller pattern that most of Cocoa is built around.

视图控制器可以更直接地与他们的孩子交互,但仍然不应该直接修改IBOutlets 。他们应该设置属性。子视图控制器有责任在正确的时间将该数据从属性移动到标签(可能必须等到 viewDidLoad())。这就是它被称为视图控制器的原因。它是负责其观点的一个对象。别人不应该搞砸他们。

View controllers may interact more directly with their children, but still should not modify IBOutlets directly. They should set properties. It is the child view controller's responsibility to move that data from the property to the label at the correct time (which may have to wait until viewDidLoad()). That's why it's called the "view controller." It is the one object responsible for its views. No one else should mess with them.

这篇关于如何从另一个类访问IBOutlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆