在使用UIPickerView展开Optional值时,意外地发现了nil

时间:2018-02-12 08:30:05

标签: ios swift uipickerview

我最近转向了iOS(Swift)。在UIPickerView工作时,我遇到了这个错误:

  

致命错误:在解包可选值时意外发现nil

我为UIPickerViewDataSourceUIPickerViewDelegate创建了一个外部课程。

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收到列表时调用的。然后我就是这样设置UIPickerViewDataScourceUIPickerViewDelegate

func onCampusResponseSuccess(response: CampusListResponse) {

    let listOfCampus = convertToCampusListModel(apiResponse: response) 
    campusPickerData = CampusPickerData(list: listOfCampus)
    campusPicker.dataSource = campusPickerData // Here is the ERROR
    campusPicker.delegate = campusPickerData

}

如何解决此问题。请注意,UIPickerViewDataSourceUIPickerViewDelegate必须有单独的课程。

我能找到这些参考文献!

Manage a UIPickerView from an External Class - Using Swift

Custom data source class for UIPickerView in Swift

由于

0 个答案:

没有答案