Reputation: 95
I get the error in the title while trying to change the text of a label which is part of the Page class (a subclass of UIViewController)
@IBAction func StartButton(sender: AnyObject) {
for quote in quoteList {
var newPage = Page()
//error is on the next line:
newPage.Label.text = quote
pageArray!.append(newPage)
}
}
}
and here is the Page class:
class Page : UIViewController{
var index: Int = 0
var parent: PageArray?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var Label: UILabel!
@IBAction func previousButton(sender: AnyObject) {
}
@IBAction func gotoListButton(sender: AnyObject) {
}
@IBAction func nextButton(sender: AnyObject) {
}
}
I am new when it comes to swift programming, and iOs in general; I apologise if a similar question has already been asked. I searched first, but didn't find a solution that worked for me. I suspect the problem is with the initialization of newPage, and tried doing it a few different ways, but I can't seem to get it right. My question is what exactly am I doing wrong, and how can I fix it?
EDIT: Got it working like this (by working I mean not crashing and doing nothing):
@IBAction func StartButton(sender: AnyObject) {
var pageArray: PageArray = PageArray()
for quote in quoteList {
var newPage = Page(nibName: "Page", bundle: nil)
if newPage.Label != nil {
newPage.Label.text = quote
}
pageArray.append(newPage)
}
}
It seems certain now that newPage.Label is nil.
Upvotes: 1
Views: 1035
Reputation: 7582
I knew your problems. When you load a ViewController from Nib. Actually It's take a delay time until your ViewController has been loaded.
This code below help your ViewController load immediate.
@IBAction func StartButton(sender: AnyObject) {
var pageArray: PageArray = PageArray()
for quote in quoteList {
var newPage = Page(nibName: "Page", bundle: nil)
let _ = newPage.view // A trick. It's help your view load immediate
// Your Page has been loaded.
newPage.Label.text = quote
pageArray.append(newPage)
}
Upvotes: 0
Reputation: 9144
Well, pageArray
is probably nil and with !
you are pretending that it is not.
Instantiating pageArray should solve your issue.
You can check the first answer here to learn more about question and exclamation marks in swift
EDIT:
Your problem might also come from your controller initialization, you might want to try:
let mystoryboard:UIStoryboard = UIStoryboard(name: "storyboardName", bundle: nil)
var newPage:Page = mystoryboard.instantiateViewControllerWithIdentifier("idYouAssigned") as! Page
Upvotes: 4