根据mode/case改变navigationBar.title?

Changing navigationBar.title according to mode/case?

我有 viewController,它有三种 cases/three 模式。

它有一个 'Create New Person' 模式,一个 'Show Person' 模式,最后一个 'Edit Person' 模式。这一切都很好 - 但我似乎无法根据 mode/case 设置 navigationBar.title。

相关代码如下:

private func modeUpdate() {
   let createNewPerson:[NSAttributedString.Key: Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue):UIColor.blue, NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):UIFont(name:"Create New Person", size: 17)!]
   let showPerson:[NSAttributedString.Key: Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue):UIColor.blue, NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):UIFont(name:"", size: 17)!]
   let editPerson:[NSAttributedString.Key: Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue):UIColor.blue, NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue):UIFont(name:"Edit Person", size: 17)!]


    switch mode {
    case .create:
        actionButton.title = "Save"
        personName.isEditable = true
        navigationController?.navigationBar.titleTextAttributes = createNewPerson
        question.isEditable = false
        personAnswer.isEditable = true
        extraIdentifier.isEditable = false
        extraIdentifierAnswer.isEditable = true

    case .show:
        actionButton.title = "Edit"
        navigationController?.navigationBar.titleTextAttributes = showPerson
        personName.isEditable = false
        question.isEditable = false
        personAnswer.isEditable = false
        extraIdentifier.isEditable = false
        extraIdentifierAnswer.isEditable = false

    case .edit:
        actionButton.title = "Save"
        navigationController?.navigationBar.titleTextAttributes = editPerson
        personName.isEditable = true
        question.isEditable = false
        personAnswer.isEditable = true
        extraIdentifier.isEditable = false
        extraIdentifierAnswer.isEditable = true
    }
}

全部编译,但是当我在我的设备上输入三种情况中的任何一种时,我在 'let createNewPerson:[NSAttributed....'

行得到:'Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value'

有谁知道为什么会这样?

谢谢!

试试这个 self.navigationItem.title = "text"