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

问题描述 投票:0回答:1

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

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的字符串变量,它根据用户在启动时选择的语言作为标题值来更改值。

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

变量selectedLanguage在languageMenu方法中设置如此(不知道前2行的格式化发生了什么!):

导入UIKit

class ViewController: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")
        }
    }
}
ios swift variables navigationbar titlebar
1个回答
1
投票

目前只有一个地方你正在设置title,那就是viewDidLoad。基本上,每次chosenLanguage改变时,你需要将title分配给chosenLanguage

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

(如果你在没有值类型的Objective-C中写这个,那么同样的事情会发生,因为title属性使用copy属性。)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.