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

时间:2019-03-11 20:32:55

标签: ios swift variables navigationbar titlebar

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

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”)上可以正常使用。 我想使用一个名为selectedLanguage的字符串变量,该变量会根据用户在启动时选择哪种语言作为title的值来更改值。

尝试此操作时,导航栏标题区域中未显示任何内容。在网上搜索时,没有看到任何此类示例。

像这样在languageMenu方法中设置了selectedLanguage变量(不知道格式化前两行会发生什么!):

导入UIKit

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")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

当前只有一个位置要设置title,该位置位于viewDidLoad中。基本上,每次chosenLanguage更改时,您需要将title分配给chosenLanguage

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

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