Swift PickerView label error

时间:2015-07-29 00:35:44

标签: ios xcode swift

Animation anim1 = new AlphaAnimation (1, 0.5F);
anim1.setDuration (600); //The slow part.
//set other things for anim1

Animation anim2 = new AlphaAnimation (0.5F, 0);
anim2.setDuration (200); //The fast part.
//set other things for anim2

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet var picker: UIPickerView! @IBOutlet var label: UILabel!

import UIKit

}

could you explain to me the difference between the error row and row that I used for title above?

why I would get error for the bottom one. I declare correctly I think.

1 个答案:

答案 0 :(得分:1)

(我假设您希望在用户点按按钮时更改标签的文字)

此函数在pickerView的值发生更改时运行(您尝试使用的row参数,在执行pickerView时运行,而不是在值发生更改时运行) -

 func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)

此外,您要创建一个全局变量,以便在row函数中使用row(didSelectRow函数中的IBAction参数只能在该函数内使用)。

所以在类定义下添加这段代码 -

var rowSelected = 0

接下来,将此功能添加到您的代码中 -

 func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      rowSelected = row
}

最后,将label.text = Array[row]更改为label.text = Array[rowSelected](这也会使您的未解析标识符错误消失)。

所以你的整个代码应该是这样的 -

var rowSelected = 0
var Array = ["Iphone", "겔럭시", "베가아이언"]

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

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return Array[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return Array.count
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}
@IBAction func buttonTapped(sender: AnyObject) {
       label.text = Array[rowSelected]


}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      rowSelected = row
}

希望这很有效。