PickerView的使用需实现UIPickerViewDelegate,UIPickerViewDataSource这两个协议
class ViewController: UIViewController ,UIPickerViewDelegate,UIPickerViewDataSource {
var pickerData: NSDictionary! //保存全部数据的字典
var pickerProvincesData: NSArray! //保存当前省数据的数组
var pickerCitiesData: NSArray! //保存当前省下面市数据的数组
var pickerView: UIPickerView!
var LabelPickerView: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let plistPath = Bundle.main.path(forResource: "provinces_cities", ofType: "plist")
let dict = NSDictionary(contentsOfFile: plistPath!)
self.pickerData = dict
self.pickerProvincesData = self.pickerData.allKeys as NSArray!
//默认取出第一个省的所有市的数据
let selectedProvince = self.pickerProvincesData[0] as! NSString
self.pickerCitiesData = self.pickerData[selectedProvince] as! NSArray
//添加选择器
self.pickerView = UIPickerView(frame: CGRect(x: (screen.size.width/2 + 10), y: 160, width: screen.size.width/2 - 30, height: 200))
self.view.addSubview(pickerView)
self.pickerView.dataSource = self
self.pickerView.delegate = self
//添加label
LabelPickerView = UILabel(frame: CGRect(x: (screen.size.width/2 + 10), y: 400, width: screen.size.width/2 - 30, height: 30))
self.LabelPickerView.text = "LabelPickerView"
self.LabelPickerView.textAlignment = .center//字体居中
self.view.addSubview(LabelPickerView)
}
参考自关东升的《开发指南》