我最近转向了iOS(Swift)。在UIPickerView
工作时,我遇到了这个错误:
致命错误:在解包可选值时意外发现nil
我为UIPickerViewDataSource
和UIPickerViewDelegate
创建了一个外部课程。
CampusPickerData
class CampusPickerData: NSObject, UIPickerViewDataSource, UIPickerViewDelegate{
var campusList = [CampusListModel]()
init(list : [CampusListModel]){
campusList.removeAll()
for item in list {
let newItem = CampusListModel(locationId: item.locationId, description: item.description)
campusList.append(newItem)
}
let size = campusList.count // Doesn't get count as well
print(size)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return campusList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
return campusList[row].description
}
}
这就是我在ViewController中设置它的方式:
class SelectPatientViewController: UIViewController, CampusResponseProtocol{
// .. Other properties
private var campusPickerData : CampusPickerData!
如您所见,SelectPatientViewController
还实现了CampusResponseProtocol
,它是从Web API收到列表时调用的。然后我就是这样设置UIPickerViewDataScource
和UIPickerViewDelegate
。
func onCampusResponseSuccess(response: CampusListResponse) {
let listOfCampus = convertToCampusListModel(apiResponse: response)
campusPickerData = CampusPickerData(list: listOfCampus)
campusPicker.dataSource = campusPickerData // Here is the ERROR
campusPicker.delegate = campusPickerData
}
如何解决此问题。请注意,UIPickerViewDataSource
和UIPickerViewDelegate
必须有单独的课程。
我能找到这些参考文献!
Manage a UIPickerView from an External Class - Using Swift
Custom data source class for UIPickerView in Swift
由于