Swift 4.2-PickerView不显示内容

时间:2018-12-27 10:19:11

标签: ios swift

这段代码让我非常生气。我已经阅读了成千上万的教程和堆栈溢出注释。...

请帮助我。选择器仅包含一个空白的灰色屏幕。

此处的代码:

GenderPickerModel.swift

    import UIKit

class GenderPickerModel:  NSObject, UIPickerViewDataSource, UIPickerViewDelegate {

    let genderPickerData: [String] = ["male", "female"]

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1;
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return genderPickerData.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return genderPickerData[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    } 
}

并在控制器中使用:

@IBOutlet weak var gender: UITextField!  
private var genderPickerView: UIPickerView?

override func viewDidLoad() {
        super.viewDidLoad()
        loadProfile()
        prepareView()
    }

    func prepareView() {
        genderPickerView = UIPickerView.init()

        let gpModel = GenderPickerModel()

        genderPickerView?.delegate = gpModel
        genderPickerView?.dataSource = gpModel
        gender.inputView = genderPickerView;
        genderPickerView?.selectRow(0, inComponent: 0, animated: true)
        genderPickerView?.reloadAllComponents()
    }

1 个答案:

答案 0 :(得分:3)

首先,您无需在pickerview类中进行单独的性别排序,也无需创建pickerview实例。

由此,您可以在custompicker视图中查看数据源

/**
Controller code where you can create instantiate picker assign data 

*/
    class ViewController: UIViewController {

        @IBOutlet weak var textField: UITextField!            
        let genderPickerData : [String] = ["male", "female"]

        override func viewDidLoad() {
            super.viewDidLoad()

            prepareView()
        }

        func prepareView() {

            genderPickerView = UIPickerView()

            let gpModel = GenderPickerModel()

            gpModel.data = genderPickerData

            gpModel.dataSource = gpModel
            gpModel.delegate = gpModel
            textField.inputView = gpModel

        }
    }

/**

Custom pickerview class where you can handle data 

*/
import UIKit

class GenderPickerModel: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {

    var data = [String]()

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return data[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    }

}