我有一个PickerView和这样的标签:
我想,当我更改组件中每一行的值时,它会将值分配给上面的标签。
例如:当我在第一个组件中选择“Blue”而在第二个组件中选择“Two”时,它会将“Blue Two”分配给Label。
我尝试过这样,但是效果不好,当我在第二个组件中选择第六个值时会崩溃:
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet var colorLabel: UILabel!
let colors = ["Red", "Green", "Blue", "Black", "White"]
let numbers = ["One", "Two", "Three", "Four" ,"Five", "Six", "Seven"]
var array = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
array = [colors, numbers]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return array.count
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return array[component].count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return array[component][row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
colorLabel.text = component == 0 ? array[component][row] + " " + array[component][row] : array[component][row] + " " + array[component][row]
}
}
答案 0 :(得分:1)
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var selectedValueFirstRow = pickerView.selectedRowInComponent(0)
var selectedValueSecondRow = pickerView.selectedRowInComponent(1)
colorLabel.text = colors[selectedValueFirstRow] + " " + numbers[selectedValueSecondRow]
}
您的代码崩溃了,因为它超出了第一个数组的索引
答案 1 :(得分:0)
我在ViewController
的顶部添加这些行var colorString = ""
var numberString = ""
并更改didSelectRow函数,如下所示:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
colorString = array[component][row]
} else {
numberString = array[component][row]
}
resultLabel.text = colorString + " " + numberString
}
现在效果很好。