我正在尝试开发一个应用程序,现在我想通过2个不同的UIPickerViews的输入来编辑标签的文本。
起初我会收到错误。
"thread 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0)"
指着一些代码(见代码),但现在我只得到错误
"fatal error: Index out of range"
问题在于第一个选择器,如果我在那里更改任何东西(在模拟器中!),应用程序崩溃了。如果我仅更改第二个选择器然后更新标签,则更改为“1天”或“2周”,而不是仅仅“天”或“周”。
我的故事板:
我的代码:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var PickerView1: UIPickerView!
@IBOutlet weak var PickerView2: UIPickerView!
@IBOutlet weak var outputLabel: UILabel!
@IBAction func changeLabel(_ sender: UIButton) {
outputLabel.text = outputTotal
}
var list1 = [""]
var list2 = [""]
var output1 = ""
var output2 = ""
var outputTotal = ""
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// Aangeven welke items er in de pickerview komen
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (pickerView.tag == 1){
return "\(list1[row])"
} else {
return "\(list2[row])"
}
}
// Aantal rijen weergeven
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (pickerView.tag == 1){
return list1.count
} else {
return list2.count
}
}
// Label veranderen naar input van PickerView1
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
output1 = list1[row]
output2 = list2[row] // error points here
outputTotal = output1 + " " + output2
}
override func viewDidLoad() {
list1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
list2 = ["days", "weeks"]
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如果有人可以帮助我,谢谢你!
答案 0 :(得分:1)
我想你忘了检测pickView
中选择的pickerView(_:didSelectRow:inComponent:)
:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 1 {
output1 = list1[row]
} else {
output2 = list2[row]
}
outputTotal = output1 + " " + output2
}