在viewDidLoad中使用Variable

时间:2014-11-21 20:42:32

标签: xcode variables swift viewdidload

标签etikett1确实正确输出变量test1的值,但标签etikett2无效。我怎样才能获得viewDidLoad中声明的变量test2的值?

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var etikett1: UILabel!
    @IBOutlet weak var etikett2: UILabel!

    @IBAction func button(sender: UIButton) {
        let test1 = "hello 1"
        etikett1.text = test1  
        etikett2.text = test2       
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let test2 = "hello 2"
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将test2声明为实例变量以及两个标签,或者在text内指定etikket2 viewDidLoad属性:

方法1:

class ViewController: UIViewController {
    @IBOutlet weak var etikett1: UILabel!
    @IBOutlet weak var etikett2: UILabel!
    let test2 = "hello 2"

    @IBAction func button(sender: UIButton) {
        let test1 = "hello 1"
        etikett1.text = test1  
        etikett2.text = test2       
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

方法2:

override func viewDidLoad() {
    super.viewDidLoad()
    let test2 = "hello 2"
    etikett2.text = test2
}