gpt4 book ai didi

ios - Swift UIPickerView 标签错误

转载 作者:行者123 更新时间:2023-11-28 07:02:37 25 4
gpt4 key购买 nike

import UIKit

类 ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet 变量选择器:UIPickerView! @IBOutlet 变量标签:UILabel!

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[row] ///this part error "use of unresolved identifier row"


}

你能给我解释一下错误行和我在上面标题中使用的行之间的区别吗?

为什么我会得到底部的错误。我认为我声明正确。

最佳答案

(我假设您希望标签的文本在用户点击按钮时发生变化)

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

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

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

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

var rowSelected = 0

接下来,将此函数添加到您的代码中 -

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

最后,更改 label.text = Array[row]label.text = Array[rowSelected] (这也应该使您 Unresolved 标识符错误消失)。

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

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
}

希望一切顺利。

关于ios - Swift UIPickerView 标签错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31689390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com