IBOutlet of another view controller is nil

南楼画角 提交于 2019-12-17 16:50:21

问题


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!

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()

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


回答1:


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)


来源:https://stackoverflow.com/questions/28741399/iboutlet-of-another-view-controller-is-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!