iOS多级联动选择器,地址、时间选择(Swift3.0版)

iOS控件UIPickerView和DatePicker可实现滑动选择功能。基于UIPickerView封装多级联动(必须将可供选择的数据缓存本地),如省市区选择实现,效果如下:
Simulator Screen Shot 01.png

自定义LmyPickerObject类,定义要显示的标题、下一集子菜单集合,如果选择省市区可添加属性code。

public class LmyPickerObject: NSObject {
    
    var title:String?
    var subArray:[LmyPickerObject]?
    var code:String?
}

设置枚举,融合两种选择器可配置,还可添加其他可操作功能实现我们想要的效果。

public enum LmyPickerStyle : Int32 {
    
    case nomal
    
    case date
}

protocol PickerDelegate : NSObjectProtocol {

    func chooseElements(picker: LmyPicker, content: [Int:Int])
    func chooseDate(picker: LmyPicker, date: Date)
}

初始化LmyPicker,init方法

    var pickerDelegate : PickerDelegate?
    
    private let picker_height:CGFloat! = 260
    private var picker: UIPickerView = UIPickerView()
    private var datePicker: UIDatePicker = UIDatePicker()
    private var content: [LmyPickerObject]?
    private var pickerStyle: LmyPickerStyle?
    private var backgroundBtn: UIButton = UIButton()
    private var tempDic: Dictionary = [Int:Int]()
    private var numComponents:Int = 0
    
    var contentArray:[LmyPickerObject]? {
        get {
            return self.content
        }
        set {
            self.content = newValue
            self.initializeContentArray()
        }
    }

    init(delegate: PickerDelegate, style: LmyPickerStyle) {
        pickerDelegate = delegate
        pickerStyle = style
        let v_frame = CGRect(x: 0, y: UIScreen.height, width: UIScreen.width, height: picker_height)
        super.init(frame: v_frame)
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 44))
        view.backgroundColor = UIColor.RGBA(230, 230, 230, 1)
        self.addSubview(view)
        
        let cancelBtn = UIButton(type: UIButtonType.system)
        cancelBtn.frame = CGRect(x: 0, y:  0, width: 60, height: 44)
        cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        cancelBtn.setTitle("取 消", for: UIControlState.normal)
        cancelBtn.setTitleColor(UIColor.RGBA(18, 93, 255, 1), for: UIControlState.normal)
        cancelBtn.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
        self.addSubview(cancelBtn)
        
        let doneBtn = UIButton(type: UIButtonType.system)
        doneBtn.frame = CGRect(x: UIScreen.width - 60, y: 0, width: 60, height: 44)
        doneBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        doneBtn.setTitle("确 定", for: UIControlState.normal)
        doneBtn.setTitleColor(UIColor.RGBA(18, 93, 255, 1), for: UIControlState.normal)
        doneBtn.addTarget(self, action: #selector(doneButtonClick), for: .touchUpInside)
        self.addSubview(doneBtn)
        
        backgroundBtn = UIButton(type: UIButtonType.system)
        backgroundBtn.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height)
        backgroundBtn.backgroundColor = UIColor.RGBA(0, 0, 0, 0.0)
        switch style {
        case .nomal:
            self.picker = UIPickerView(frame: CGRect(x: 0, y: 44, width: UIScreen.width, height: picker_height - 44))
            self.picker.delegate = self
            self.picker.dataSource = self
            self.picker.backgroundColor = UIColor.white
            self.addSubview(self.picker)
        case .date:
            self.datePicker = UIDatePicker(frame: CGRect(x: 0, y: 44, width: UIScreen.width, height: picker_height - 44))
            self.datePicker.datePickerMode = UIDatePickerMode.date
            self.datePicker.locale = Locale(identifier: "zh_CN")
            self.datePicker.backgroundColor = UIColor.white
            self.datePicker.addTarget(self, action: #selector(self.dateChoosePressed(datePicker:)), for: .valueChanged)
            self.addSubview(self.datePicker)
        }
    }
    private func initializeContentArray() {
        
        var temp:Int = 0
        if let array = content {
            if array.count > 0 {
                temp = 1
                tempDic[temp - 1] = 0
                var object = array.first
                while object?.subArray != nil {
                    temp += 1
                    tempDic[temp - 1] = 0
                    let arr = object?.subArray
                    if let temp_arr = arr {
                        if temp_arr.count > 0 {
                            object = temp_arr.first
                        }else {
                            break
                        }
                    }else{
                        break
                    }
                }
            }
        }
        numComponents = temp
        picker.reloadAllComponents()
    }
    public func show() {
        UIApplication.shared.keyWindow?.addSubview(self.backgroundBtn)
        UIApplication.shared.keyWindow?.addSubview(self)
        UIView.animate(withDuration: 0.35, animations: {
            self.backgroundBtn.backgroundColor = UIColor.RGBA(0, 0, 0, 0.3)
            self.top = UIScreen.height - self.picker_height
        }) { (finished: Bool) in
        }
    }
    private func hiddenPicker() {
        UIView.animate(withDuration: 0.35, animations: {
            self.backgroundBtn.backgroundColor = UIColor.RGBA(0, 0, 0, 0.0)
            self.top = UIScreen.height
        }) { (finished: Bool) in
            for view in self.subviews {
                view.removeFromSuperview()
            }
            self.removeFromSuperview()
            self.backgroundBtn.removeFromSuperview()
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

UIPickerViewDelegate,UIPickerViewDataSource 时间方法,数据处理关键:

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return numComponents
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    var row:Int = 0
    if let array = content {
        var tempArray:Array = array
        for i in 0...numComponents {
            let value:Int = tempDic[i] ?? 0
            if component == i {
                row = tempArray.count
            }
            if tempArray.count > value {
                let object = tempArray[value]
                if let arr = object.subArray {
                    tempArray = arr
                }else {
                    tempArray = [LmyPickerObject]()
                }
            }
            if component == i {
                return row
            }
        }
        return 0
    }
    return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if pickerStyle == .nomal {
        self.picker_partingLine(color: UIColor.lightGray)
    }
    var str:String = ""
    if let array = content {
        var tempArray:Array = array
        for i in 0...numComponents {
            let value:Int = tempDic[i] ?? 0
            if component == i {
                let object = tempArray[row]
                str = object.title ?? "未知"
            }
            if tempArray.count > value {
                let object = tempArray[value]
                if let arr = object.subArray {
                    tempArray = arr
                }else {
                    tempArray = [LmyPickerObject]()
                }
            }
        }
        return str
    }
    return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    tempDic.updateValue(row, forKey: component)
    if (component + 1) < numComponents {
        for i in (component+1)..<numComponents {
            tempDic.updateValue(0, forKey:i)
            pickerView.selectRow(0, inComponent: i, animated: false)
        }
    }
    pickerView.reloadAllComponents()
}
func dateChoosePressed(datePicker: UIDatePicker) {
    //print("select date \(datePicker.date.string_from(formatter: "yyyy-MM-dd"))")
}

点击取消或确定,将结果传到相应控制器:

func doneButtonClick() {
    if pickerStyle == .nomal {
        pickerDelegate?.chooseElements(picker: self, content: tempDic)
    }else {
        pickerDelegate?.chooseDate(picker: self, date: datePicker.date)
    }
    self.hiddenPicker()
}
func cancelButtonClick(btn:UIButton) {
    self.hiddenPicker()
}

另外,不知为何从iOS10开始UIPickerView显示选项分割线消失了,从网上找到代码完美解决,应该是默认clearColor了。

func picker_partingLine(color: UIColor?) {
    let sep_color = color ?? UIColor.lightGray
    if #available(iOS 10.0, *) {
        for view in picker.subviews {
            if view.height < 1 {
                view.backgroundColor = sep_color
            }
        }
    }
}
    
结束

源码下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容