iOS/swift之UIPickView

宋嘉懿
2023-12-01

1.********************UIPickView****************

/**
 UIPickView、省市区
 需要注意的问题:同时滑动两列崩溃,解决办法:判断后执行
 使用:
 
 let provincepick =    LYBUIPickView.init(frame: CGRect(x: 10, y: 0, width: WIDTH, height: 300))
 provincepick.provinceCityAreaBlock={
 (province,city,area)in
 print("\(province)---\(city)---\(area)")
 
 }
 view.addSubview(provincepick)
 
 
 */
import UIKit

class LYBUIPickView: UIView,UIPickerViewDelegate,UIPickerViewDataSource {
    
    var pickerView:UIPickerView!
    var modelArr:[LYBprovinceModel]?//所有数据的模型数组
    var provincemodel:LYBprovinceModel?//省模型
    var citymodel:LYBCityModel?//市模型
 
    var provinceStr:String?=""//省
    var cityStr:String?=""//市
    var area:String?=""//区
    
    //定义一个闭包把省市区数据传出去
    var provinceCityAreaBlock:(_ province:String,_ city:String,_ area:String)->()={(province:String,city:String,area:String)->()in}
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        createDatePickview(frame: frame)
       
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //确认或取消按钮
    @objc func sureOrcanceBtnClick(sender:UIButton){
        switch sender.tag {
        case 20://取消
            self.removeFromSuperview()
            break
            
        case 21:
             self.provinceCityAreaBlock(provinceStr!,cityStr!,area!)
              self.removeFromSuperview()
            break
            
        default: break
            
        }
    }
    //解析省市区数据
    func parseDate(){
        let path=Bundle.main.path(forResource: "shengshiquxianarea.plist", ofType: nil)
        let proviceDataArr:NSArray = NSArray(contentsOfFile:path!)!
        modelArr=([LYBprovinceModel].deserialize(from: proviceDataArr) as! [LYBprovinceModel])
//        print("\(modelArr?.first?.cities?.first?.areas)")
    }
    
    //设置默认的省市区字符串
    func setDefaultProvinceCityArea(){
        provincemodel=modelArr![0]//默认选中第一个省的模型
        provinceStr=provincemodel?.state//省名称
        if((provincemodel?.cities?.count)!>0){
            cityStr=provincemodel?.cities?.first?.city//城市,默认先选第一个
            if((provincemodel?.cities?.first?.areas?.count)!>0){
                area = provincemodel?.cities?.first?.areas?.first//区,默认先选第一个
            }
        }
        
    }
    
    func createDatePickview(frame: CGRect){
        parseDate()
        setDefaultProvinceCityArea()//设置默认的省市区
        //取消和确定按钮
        let buttonView=UIView.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: 50))
        addSubview(buttonView)
        let cancelBtn=UIButton.init(frame: CGRect.init(x: 20, y: 0, width: 100, height: 50))
        cancelBtn.setTitle("取消", for: UIControl.State.normal)
        cancelBtn.tag=20
        cancelBtn.addTarget(self, action: #selector(sureOrcanceBtnClick), for: UIControl.Event.touchUpInside)
        buttonView.addSubview(cancelBtn)
        
        let sureBtn=UIButton.init(frame: CGRect.init(x: WIDTH-150, y: 0, width: 100, height: 50))
        sureBtn.setTitle("确定", for: UIControl.State.normal)
        sureBtn.tag=21
        sureBtn.addTarget(self, action: #selector(sureOrcanceBtnClick), for: UIControl.Event.touchUpInside)
        buttonView.addSubview(sureBtn)
        
        //初始化UIPickerView
        pickerView = UIPickerView.init(frame: CGRect(x:0, y:50, width:WIDTH, height:frame.size.height-50))
        pickerView.dataSource = self
        pickerView.delegate = self
        //设置选择框的默认值
        pickerView.selectRow(0,inComponent:0,animated:true)
        addSubview(pickerView)
    }
    
    
    
    //设置选择框的列数为3列,继承于UIPickerViewDataSource协议
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    //设置选择框的行数,继承于UIPickerViewDataSource协议
    func pickerView(_ pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int {
        if component==0 {
            return (modelArr?.count)!
            
        }else if(component==1){
            let provincenum=pickerView.selectedRow(inComponent: 0)//第一列选中的行号
            provincemodel=modelArr![provincenum]//选中的省的模型
            return (provincemodel!.cities?.count)!
        }else if(component==2){
            let citynum=pickerView.selectedRow(inComponent: 1)//第2列选中的行号
            if((provincemodel?.cities?.count)!>citynum){
                 citymodel=provincemodel?.cities![citynum]//选中的城市模型
            }
           
            return (citymodel?.areas?.count)!
        }
        return 0
    }
    //设置选择框各显示的内容,继承于UIPickerViewDelegate协议
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
                    forComponent component: Int) -> String? {
        if(component==0){
            provincemodel=modelArr![row]
            return provincemodel?.state
        }else if(component==1){
            if((provincemodel?.cities?.count)!>row){
            citymodel=provincemodel?.cities![row]//选中的城市模型
            }
            return citymodel!.city
            
        }else if(component==2){
            if(citymodel!.areas!.count>row){
                 return citymodel!.areas![row];
            }
          
        }
        return ""
    }
    
    //    //自定义返回每一行返回的内容,如果设置了这个自定义的,上面的titlefor view就被覆盖了
    //    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    //
    //        return UIView.init()
    //    }
    
    //选中某一行
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component==0 {
            let  provinceIndex=pickerView.selectedRow(inComponent: 0)//第一列选中的行号
            provincemodel=modelArr![provinceIndex]//选中的省的模型
            provinceStr=provincemodel?.state//省
            if((provincemodel?.cities?.count)!>0){
                 pickerView.reloadComponent(1)
                 pickerView.selectRow(0, inComponent: 1, animated: true)
                cityStr=provincemodel?.cities?.first?.city//城市,默认先选第一个
                 area=""//如果是澳门国外等没有第三列,在这里置为空,要不然就会显示最有一个数据
                if((provincemodel?.cities?.first?.areas?.count)!>0){
                  area = provincemodel?.cities?.first?.areas?.first//区,默认先选第一个
                }
                  pickerView.reloadComponent(2)
            }
           
           
         
        }else if(component==1){
            let citynum=pickerView.selectedRow(inComponent: 1)//第1列选中的行号
            citymodel=provincemodel?.cities![citynum]//选中的城市模型
            cityStr=citymodel?.city//选中的城市
             pickerView.reloadComponent(2)
            area=""//如果是澳门国外等没有第三列,在这里置为空,要不然就会显示最有一个数据
            if((citymodel?.areas?.count)!>0){
                area=citymodel?.areas?.first
                pickerView.selectRow(0, inComponent: 2, animated: true)
            }
            
           
        }else if(component==2){
            let areaIndx=pickerView.selectedRow(inComponent: 2)//第2列选中的行号
            let citynum=pickerView.selectedRow(inComponent: 1)//第1列选中的行号
            citymodel=provincemodel?.cities![citynum]//选中的城市模型
             if((citymodel?.areas?.count)!>0){
                area=citymodel?.areas![areaIndx]
            }
        }
        self.provinceCityAreaBlock(provinceStr!,cityStr!,area!)
//         print("\(provinceStr)---\(cityStr)---\(area)")
    }
    
}

 

 类似资料: