设置变量的值不断变化

时间:2015-01-14 15:56:21

标签: swift uisegmentedcontrol optional

我正在尝试创建一个多语言应用。有一个UISegmented控制栏,有三个语言的3段。我已经创建了将保存该值的语言变量(英语 - 0,广东话 - 1,普通话 - 2)。我的问题是,在模拟器中,当我更改选定的段控件时,语言变量将随机更改,即使每个段应将变量更改为特定变量。

谁能告诉我我做错了什么?

class About: UIViewController {

var language: Int?
@IBOutlet weak var selectLanguage: UISegmentedControl!
@IBOutlet weak var whatIsiEd: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

func checkLanguage() -> Int? {
    return language
}

@IBAction func setLanguage(sender: AnyObject) {
    if self.selectLanguage.selectedSegmentIndex == 0 {
        println("Language is set to English - \(language) - \(self.selectLanguage.selectedSegmentIndex)")
        language = 0
    } else if self.selectLanguage.selectedSegmentIndex == 1 {
        println("Language is set to Traditional Chinese - \(language) - \(self.selectLanguage.selectedSegmentIndex)")
        language = 1
    } else if self.selectLanguage.selectedSegmentIndex == 2 {
        println("Language is set to Simplified Chinese - \(language) - \(self.selectLanguage.selectedSegmentIndex)")
        language = 2
    }
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

默认情况下,当我使用模拟器时,段控制器设置为英语(段0)。然后我更改为段1,然后是2,然后返回到1,最后是0.日志报告以下内容:

语言设为繁体中文 - nil - 1
语言设置为简体中文 - 可选(1) - 2
语言设置为繁体中文 - 可选(2) - 1
语言设置为英语 - 可选(1) - 0

1 个答案:

答案 0 :(得分:1)

从评论中找到。您只是在为language分配正确的值之前记录它。在这种情况下,如果您只是交换language的分配和print语句,那么您应该是好的:

@IBAction func setLanguage(sender: AnyObject) {
    if self.selectLanguage.selectedSegmentIndex == 0 {
        // Assignment
        language = 0
        // Then print. Now your result will be correct.
        println("Language is set to English - \(language) - \(self.selectLanguage.selectedSegmentIndex)")
    } else if ...
}