提问者:小点点

segue.destination中的UILabel-在隐式展开可选值时意外发现nil


我有一个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

因此,namelabelnil。我不知道为什么。


共1个答案

匿名用户

解决方案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"]!
    
}