从表视图到视图控制器执行Segue时出现问题

时间:2019-05-01 11:00:53

标签: ios swift uitableview uistoryboardsegue

我正在尝试从UITableView进行新闻采访。如果您推送新闻之一,它将对您选择的特定新闻进行搜索。

这很容易,我已经做过几次……但是我不知道这次我在做什么错。

NewsDetailViewController 像这样:

class NewsDetailViewController: UIViewController {

@IBOutlet weak var newsImage: UIImageView!
@IBOutlet weak var newsTitle: UILabel!
@IBOutlet weak var newsDate: UILabel!
@IBOutlet weak var newsText: UILabel!

var newsLink: String?

override func viewDidLoad() {
    super.viewDidLoad()

    // Hides the navigation bar.
    self.navigationController?.setNavigationBarHidden(true, animated: false)

}


@IBAction func closeNews(_ sender: UIButton) {
       navigationController?.popViewController(animated: true)

}

}

NewsTableViewController 中的序列如下:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    print("you selected the row: \(indexPath.row)")
    tableView.deselectRow(at: indexPath, animated: true)
    self.performSegue(withIdentifier: "goToNewsDetail", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "goToNewsDetail" {

        if let destination = segue.destination as? NewsDetailViewController {

            destination.newsLink = "whateverlink"
            destination.newsTitle.text = "whatevertitle"

        }

    }

}

行:destination.newsLink = "whateverlink" 完美运行。

但行:destination.newsTitle.text = "whatevertitle" 抛出

  

致命错误:在隐式展开一个   可选值。

我不知道该怎么办。尝试初始化目的地中的其余标签时,也会发生相同的问题。

3 个答案:

答案 0 :(得分:1)

这是问题所在

destination.newsTitle.text = "whatevertitle"

不访问目标vc的出口,因为尚未加载它们发送一个字符串并将其分配给目标vc中的标签

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToNewsDetail" {
            if let destination = segue.destination as? NewsDetailViewController {
                destination.newsLink = "whateverlink"
                destination.toSend = "whatevertitle"
        }
    }
}
class NewsDetailViewController: UIViewController {
    @IBOutlet weak var newsTitle:UILabel!
    var toSend = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.newsTitle.text = toSend
    }
}

答案 1 :(得分:1)

prepareForSegue方法中,newsTitle标签仍未初始化,因此为nil

通常,您不应在prepareForSegue中设置目标VC视图的属性。您应该在newsTitleText中声明一个NewsDetailViewController属性:

var newsTitleText: String!

并设置此属性:

destination.newsTitleText = "whatevertitle"

然后在newsTitle.text中设置viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    // Hides the navigation bar.
    self.navigationController?.setNavigationBarHidden(true, animated: false)
    newsTitle.text = newsTitleText
}

答案 2 :(得分:1)

调用prepare(for:sender:)方法时,NewsDetailViewController尚未加载视图,因此您无法在标签上设置文本。您要做的是在NewsDetailViewController上创建另一个属性,例如var newsTitleText: String?。然后在viewDidLoad中,您可以呼叫newsTitle.text = newsTitleText