使用字符串变量设置导航栏标题

Set navigation bar title using string variable

我正在这样设置我的导航栏标题:

override func viewDidLoad() {
    super.viewDidLoad()

    languageMenu()

    let titleAttributes = [NSAttributedString.Key.font: UIFont(name: "AmericanTypewriter", size: 22)!]
    navigationController?.navigationBar.titleTextAttributes = titleAttributes
    title = "POLYGLOT"

    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewWord))
}

这适用于字符串文字,即 "POLYGLOT"。 我想使用一个名为 chosenLanguage 的字符串变量,它会根据用户在启动时选择的语言作为标题的值来更改值。

尝试此操作时,导航栏标题区域没有显示任何内容。我在网上搜索时没有看到任何这方面的例子。

变量 chosenLanguage 是在 languageMenu 方法中设置的(不知道前两行的格式发生了什么!):

导入 UIKit

classViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var languageButton: UIButton!
@IBOutlet weak var tableView: UITableView!

var words = [String]()
var chosenLanguage = String()
var languageSaved = String()
var toolbar = UIToolbar()

override func viewDidLoad() {
    super.viewDidLoad()

    languageMenu()

    let titleAttributes = [NSAttributedString.Key.font: UIFont(name: "AmericanTypewriter", size: 22)!]
    navigationController?.navigationBar.titleTextAttributes = titleAttributes
    title = chosenLanguage

    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewWord))
}

@objc func languageMenu(){

    let chooseLanguage = UIAlertController(title: "Vocabulary Tutor", message: "Choose a Language", preferredStyle: .actionSheet)

    let germanButton = UIAlertAction(title: "German", style: .default, handler: { (action) -> Void in
        self.chosenLanguage = "german"
        print("Choosen language is: \(self.chosenLanguage)")
        self.loadInitialValues()
    })

    let frenchButton = UIAlertAction(title: "French", style: .default, handler: { (action) -> Void in
        self.chosenLanguage = "french"
        print("Choosen language is: \(self.chosenLanguage)")
        self.loadInitialValues()
    })

    chooseLanguage.addAction(germanButton)
    chooseLanguage.addAction(frenchButton)

    self.navigationController!.present(chooseLanguage, animated: true, completion: nil)

    if let defaults = UserDefaults(suiteName: "group.co.uk.tirnaelectronics.polyglot") {
        if chosenLanguage == "german" {
            defaults.set(chosenLanguage, forKey: "languageChosen")
        } else {
            defaults.set(chosenLanguage, forKey: "languageChosen")
        }
    }
}

目前只有一个地方可以设置 title,那就是 viewDidLoad。基本上,每次 chosenLanguage 更改时,您都需要将 chosenLanguage 分配给 title

原因是字符串在Swift中是值类型。因此,当您将一个变量赋给 title 时,您实际上是在将变量的当前值复制到 title 中。之后对变量的任何更改都不会影响 title.

(如果您在没有值类型的 Objective-C 中编写此代码,则会发生同样的事情,因为 title 属性 使用 copy 属性.)