我有一个ViewController类和我从Storyboard创建的两个IBOutture Uilablel。
下面是类的代码:
import UIKit
class AnnouncementViewController: UIViewController {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var infoTV: UITextView!
var mail: String = ""
var url: String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
func set(_ announcement: [String: String]) {
print(announcement)
nameLabel.text = announcement["name"] // here goes the error
self.infoTV.text = announcement["info"]
self.mail = announcement["email"]!
self.url = announcement["url"]!
}
}
下面是另一个类(TableViewController)的代码:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard segue.identifier == "announcementSegue" else { return }
let indexPath = tableView.indexPathForSelectedRow!
let announcement = tasks[indexPath.row]
let destinationVC = segue.destination as! AnnouncementViewController
destinationVC.set(announcement)
}
我得到的错误是:在隐式展开可选值时意外发现nil
因此,namelabel
是nil
。我不知道为什么。
解决方案1调用LoadViewIfNeeded()
let destinationVC = segue.destination as! AnnouncementViewController
destinationVC.view.loadViewIfNeeded()
destinationVC.set(announcement)
解决方案2
let destinationVC = segue.destination as! AnnouncementViewController
destinationVC.ann = announcement
var ann = [String: String]()
override func viewDidLoad() {
super.viewDidLoad()
set(ann)
}
func set(_ announcement: [String: String]) {
print(announcement)
nameLabel.text = announcement["name"] // no error
self.infoTV.text = announcement["info"]
self.mail = announcement["email"]!
self.url = announcement["url"]!
}