我在一个类中有一个对象数组,并试图将该数组引用为UIPickerView
,但是当点击UITextField
时,它崩溃并返回nil。当在countryInput文本字段上点击时,它应该显示带有“日本摩纳哥”的pickerview,依此类推...关于我在做什么的任何想法吗?预先谢谢你。
class SelectionViewController: UIViewController {
var lifeArr : [LifeClass] = []
let picker = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
let Monaco = LifeClass()
Monaco.country = "Monaco"
Monaco.male = 85.6
Monaco.female = 93.5
let Japan = LifeClass()
Japan.country = "Japan"
Japan.male = 81.9
Japan.female = 88.8
lifeArr = [Monaco, Japan]
}
}
class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var birthDayInput: UITextField!
@IBOutlet weak var countryInput: UITextField!
var selectionData : SelectionViewController!
var picker = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
picker.dataSource = self
picker.delegate = self
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return selectionData.lifeArr.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return selectionData.lifeArr[row].country
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
countryInput.text = selectionData.lifeArr[row].country
}
}
答案 0 :(得分:1)
您只声明selectionData
而不声明instantiateViewController
,这就是它发生的原因。
override func viewDidLoad() {
super.viewDidLoad()
selectionData = self.storyboard?.instantiateViewController(withIdentifier: "SelectionViewController") as! SelectionViewController
picker.dataSource = self
picker.delegate = self
}
答案 1 :(得分:1)
我认为甚至不需要使用SelectionViewController
的整个实例作为dataSource
到UIPickerView
的地方。
相反,您可以简单地在[LifeClass]
中创建SetupViewController
数组并在那里使用它。
class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
private var lifeArr = [LifeClass]()
override func viewDidLoad() {
super.viewDidLoad()
self.populateArray()
picker.dataSource = self
picker.delegate = self
}
private func populateArray() {
let monaco = LifeClass()
monaco.country = "Monaco"
monaco.male = 85.6
monaco.female = 93.5
lifeArr.append(monaco)
let japan = LifeClass()
japan.country = "Japan"
japan.male = 81.9
japan.female = 88.8
lifeArr.append(japan)
}
//Rest of the code...
}
在UIPickerViewDataSource
和UIPickerViewDelegate
方法中,使用
self.lifeArr
代替
selectionData.lifeArr
答案 2 :(得分:1)
创建一个新类以保留此数据,并在需要访问它的任何VC中使用它。例如
class LifeClassDatabase
{
var lifeArr : [LifeClass] = []
init()
{
let Monaco = LifeClass()
Monaco.country = "Monaco"
Monaco.male = 85.6
Monaco.female = 93.5
let Japan = LifeClass()
Japan.country = "Japan"
Japan.male = 81.9
Japan.female = 88.8
lifeArr = [Monaco, Japan]
}
}
例如从SetupViewController
最高层:-
private var lifeClassDatabase = LifeClassDatabase()
然后在您的数据源代码中使用它,例如:
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return lifeClassDatabase.lifeArr.count
}