另一个视图控制器的 IBOutlet 为零 [英] IBOutlet of another view controller is nil

查看:43
本文介绍了另一个视图控制器的 IBOutlet 为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 storyviewcontroller,它的视图中有对象.我需要更改 UILabel 上的文本(在 storyviewcontroller 中)并在数组上加载视图.我已将 IBOutlet 连接到 storyviewcontroller 中的标签.

I have a storyviewcontroller which has objects on its view. I need to change the text on the UILabel(In the storyviewcontroller) and the load the view on an array. I have connected the IBOutlet to the label in the storyviewcontroller.

class StoryViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var inspiredButton: UIButton!

我已经创建了 storyviewcontroller 类的对象并且能够访问它的变量.但是,在创建storyviewcontroller的对象后,IBOutlet为nil.因此,我收到一个异常,说在解包时发现 nil

I have created an object of the storyviewcontroller class and am able to access its variables. However, after creating the object of the storyviewcontroller, the IBOutlet is nil. Because of this, I get an exception saying found nil while unwrapping

let story:StoryViewController = StoryViewController()
story.textLabel.text = sampleText()

你能帮我解决这个问题吗!这是整个项目的链接https://github.com/abhishekagarwal2301/DTC谢谢

Can you please help me with this! Here is a link to the whole project https://github.com/abhishekagarwal2301/DTC Thanks

推荐答案

IBOutlets 在视图加载过程中被初始化,并且在您尝试访问它们时无法访问它们.相反,您必须向您的视图控制器声明一个字符串变量,并在其 viewDidLoad 方法上将文本设置为标签(在加载过程完成后)

IBOutlets are initialized during view loading process and they are not accessible at the point you are trying to reach them. Instead you must declare a string variable to your viewcontroller and set text to label on its viewDidLoad method (after the loading process has finished)

class StoryViewController: UIViewController {
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var inspiredButton: UIButton!
    var text:String!

   override func viewDidLoad() {
    super.viewDidLoad()

    textLabel.text = text
   }
}

从第一个控制器初始化文本变量如下

And from first controller initialize text variable as follow

let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
var story = storyboard.instantiateViewControllerWithIdentifier("YourVCIdentifier") as StoryViewController
story.text = sampleText()
self.presentViewController(story, animated: false , completion: nil)

这篇关于另一个视图控制器的 IBOutlet 为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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