Hello everybody,
I am new to iOS development and I found an error that I can not get past. I have read a lot online and on Stackoverflow but I don't understand why this error keeps coming up.
I have a table view controller and I want to write text to other view controller using:
navigationController?.pushViewController(viewController, animated: true)
I have this class where I already have an outlet for the label.
import UIKit
class PetitionDetailsViewController: UIViewController {
@IBOutlet weak var PetitionDetailsOutlet: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
On the other class I have this code where I try to add text to the label in the PetitionDetailsViewController after tapping one of the rows in the table view.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController = PetitionDetailsViewController()
print(petitions[indexPath.row].body)
viewController.PetitionDetailsOutlet.text = petitions[indexPath.row].body
navigationController?.pushViewController(viewController, animated: true)
}
I don't understand why this error keeps coming up. I have the outlet and initially the label is empty.
Why is it nil?
Sorry, I was missing one thing to make iOS build up the view hierarchy of the view controller.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController = self.storyboard!.instantiateViewController(withIdentifier: "PetitionDetailsViewController") as! PetitionDetailsViewController
_ = viewController.view //Make iOS to build the views
print(petitions[indexPath.row].body)
viewController.PetitionDetailsOutlet.text = petitions[indexPath.row].body
navigationController?.pushViewController(viewController, animated: true)
}
But this is not an ordinary way and you usually prepare another property in the target view controller and modify `viewDidLoad()`.
import UIKit
class PetitionDetailsViewController: UIViewController {
@IBOutlet weak var PetitionDetailsOutlet: UILabel!
var labelText: String?
override func viewDidLoad() {
super.viewDidLoad()
if let text = labelText {
self.PetitionDetailsOutlet.text = text
}
}
}
and
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController = self.storyboard!.instantiateViewController(withIdentifier: "PetitionDetailsViewController") as! PetitionDetailsViewController
print(petitions[indexPath.row].body)
viewController.labelText = petitions[indexPath.row].body
navigationController?.pushViewController(viewController, animated: true)
}