地址选择器swift_地址选择器 swift4 - CSDN
  • This article mainly introduces the basic usage of UIPickerView, we can obtain address information by selecting the provinces ,cities and districts

    【Summary】

    This article mainly introduces the basic usage of UIPickerView, we can obtain address information by selecting the provinces ,cities and districts.

    【Explanation and Effect Picture】

    1. The cities and districts will change when you switch the province
    2. Districts will change when you switch the city
    3. Click the confirm button,then the information label will show the address you choose

    【Preparation】

    Before we start ,we need a plist which contains all address information.
    The data format is as follows:

    This is part of the source code:

    <dict>
        <key>河北省</key>
        <dict>
            <key>石家庄市</key>
            <array>
                <string>长安区</string>
                <string>桥东区</string>
                <string>桥西区</string>
                <string>新华区</string>
                <string>井陉矿区</string>
                <string>裕华区</string>
                <string>井陉县</string>
                <string>正定县</string>
                <string>栾城县</string>
                <string>行唐县</string>
                <string>灵寿县</string>
                <string>高邑县</string>
                <string>深泽县</string>
                <string>赞皇县</string>
                <string>无极县</string>
                <string>平山县</string>
                <string>元氏县</string>
                <string>赵县</string>
                <string>辛集市</string>
                <string>藁城市</string>
                <string>晋州市</string>
                <string>新乐市</string>
                <string>鹿泉市</string>
            </array>
            <key>唐山市</key>
            <array>
                <string>路南区</string>
                <string>路北区</string>
                <string>古冶区</string>
                <string>开平区</string>
                <string>丰南区</string>
                <string>丰润区</string>
                <string>滦县</string>
                <string>滦南县</string>
                <string>乐亭县</string>
                <string>迁西县</string>
                <string>玉田县</string>
                <string>唐海县</string>
                <string>遵化市</string>
                <string>迁安市</string>
            </array>
            <key>秦皇岛市</key>
            <array>
                <string>海港区</string>
                <string>山海关区</string>
                <string>北戴河区</string>
                <string>青龙满族自治县</string>
                <string>昌黎县</string>
                <string>抚宁县</string>
                <string>卢龙县</string>
            </array>
            <key>邯郸市</key>
            <array>
                <string>邯山区</string>
                <string>丛台区</string>
                <string>复兴区</string>
                <string>峰峰矿区</string>
                <string>邯郸县</string>
                <string>临漳县</string>
                <string>成安县</string>
                <string>大名县</string>
                <string>涉县</string>
                <string>磁县</string>
                <string>肥乡县</string>
                <string>永年县</string>
                <string>邱县</string>
                <string>鸡泽县</string>
                <string>广平县</string>
                <string>馆陶县</string>
                <string>魏县</string>
                <string>曲周县</string>
                <string>武安市</string>
            </array>
            <key>邢台市</key>
            <array>
                <string>桥东区</string>
                <string>桥西区</string>
                <string>邢台县</string>
                <string>临城县</string>
                <string>内丘县</string>
                <string>柏乡县</string>
                <string>隆尧县</string>
                <string>任县</string>
                <string>南和县</string>
                <string>宁晋县</string>
                <string>巨鹿县</string>
                <string>新河县</string>
                <string>广宗县</string>
                <string>平乡县</string>
                <string>威县</string>
                <string>清河县</string>
                <string>临西县</string>
                <string>南宫市</string>
                <string>沙河市</string>
            </array>
            <key>保定市</key>
            <array>
                <string>新市区</string>
                <string>北市区</string>
                <string>南市区</string>
                <string>满城县</string>
                <string>清苑县</string>
                <string>涞水县</string>
                <string>阜平县</string>
                <string>徐水县</string>
                <string>定兴县</string>
                <string>唐县</string>
                <string>高阳县</string>
                <string>容城县</string>
                <string>涞源县</string>
                <string>望都县</string>
                <string>安新县</string>
                <string>易县</string>
                <string>曲阳县</string>
                <string>蠡县</string>
                <string>顺平县</string>
                <string>博野县</string>
                <string>雄县</string>
                <string>涿州市</string>
                <string>定州市</string>
                <string>安国市</string>
                <string>高碑店市</string>
            </array>
            <key>张家口市</key>
            <array>
                <string>桥东区</string>
                <string>桥西区</string>
                <string>宣化区</string>
                <string>下花园区</string>
                <string>宣化县</string>
                <string>张北县</string>
                <string>康保县</string>
                <string>沽源县</string>
                <string>尚义县</string>
                <string>蔚县</string>
                <string>阳原县</string>
                <string>怀安县</string>
                <string>万全县</string>
                <string>怀来县</string>
                <string>涿鹿县</string>
                <string>赤城县</string>
                <string>崇礼县</string>
            </array>
            <key>承德市</key>
            <array>
                <string>双桥区</string>
                <string>双滦区</string>
                <string>鹰手营子矿区</string>
                <string>承德县</string>
                <string>兴隆县</string>
                <string>平泉县</string>
                <string>滦平县</string>
                <string>隆化县</string>
                <string>丰宁满族自治县</string>
                <string>宽城满族自治县</string>
                <string>围场满族蒙古族自治县</string>
            </array>
            <key>沧州市</key>
            <array>
                <string>新华区</string>
                <string>运河区</string>
                <string>沧县</string>
                <string>青县</string>
                <string>东光县</string>
                <string>海兴县</string>
                <string>盐山县</string>
                <string>肃宁县</string>
                <string>南皮县</string>
                <string>吴桥县</string>
                <string>献县</string>
                <string>孟村回族自治县</string>
                <string>泊头市</string>
                <string>任丘市</string>
                <string>黄骅市</string>
                <string>河间市</string>
            </array>
            <key>廊坊市</key>
            <array>
                <string>安次区</string>
                <string>广阳区</string>
                <string>固安县</string>
                <string>永清县</string>
                <string>香河县</string>
                <string>大城县</string>
                <string>文安县</string>
                <string>大厂回族自治县</string>
                <string>霸州市</string>
                <string>三河市</string>
            </array>
            <key>衡水市</key>
            <array>
                <string>桃城区</string>
                <string>枣强县</string>
                <string>武邑县</string>
                <string>武强县</string>
                <string>饶阳县</string>
                <string>安平县</string>
                <string>故城县</string>
                <string>景县</string>
                <string>阜城县</string>
                <string>冀州市</string>
                <string>深州市</string>
            </array>
        </dict>
    

    【Function Realization】

    1. Get data from address.plist,and save it as NSDictionary in the local
      2.The addressPickView will load all provinces, we choose the first city and the first district of the city as default
    2. Realize the func of UIPickerViewDelegate and UIPickerViewDataSource,refresh the addressPickView by reloadComponent()
    3. Realize the click action of the confirm button
    
    import UIKit
    class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource{
    
        //pickerview 视图
        @IBOutlet weak var addressPickView: UIPickerView!
    
         //用于显示地址的label
        @IBOutlet weak var addressLabel: UILabel!
    
        //省 数组
        var provincesData:NSArray!
        //市 数组
        var citiesData:NSArray!
        //区 数组
        var districtsData:NSArray!
    
        //省 字典
        var provincesList:NSDictionary!
        //市 字典
        var citiesList:NSDictionary!
    
        //选择的省
        var selectedProvince:String!
        //选择的市
        var selectedCity:String!
        //选择的区
        var selectedDistrict:String!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
    
            //得到本地文件路径
            let addressPath = Bundle.main.path(forResource: "address", ofType: "plist")
            //得到字典类型数据
            let dicPList = NSDictionary(contentsOfFile: addressPath!)!
    
            self.provincesList = dicPList
            self.provincesData = self.provincesList.allKeys as NSArray!
    
            //初始化
            //默认取出第一个省、市、区的数据
            self.selectedProvince = self.provincesData[0] as! String
            self.citiesList = self.provincesList[selectedProvince] as! NSDictionary
            self.citiesData = self.citiesList.allKeys as NSArray!
            self.selectedCity = self.citiesData[0] as! String
            self.districtsData = self.citiesList[selectedCity] as! NSArray
            self.selectedDistrict = self.districtsData[0] as! String
    
            self.addressPickView.delegate = self
            self.addressPickView.dataSource = self
    
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
       //确认按钮,显示最新地址
        @IBAction func commitTapped(_ sender: Any) {
            self.addressLabel.text = "\(self.selectedProvince!)"+"\(self.selectedCity!)"+"\(self.selectedDistrict!)"
        }
    
        //UIPickerViewDataSource
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 3
        }
    
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            if component  == 0 {
                return self.provincesData.count
            }else if component == 1 {
                return self.citiesData.count
            }else{
                return self.districtsData.count
            }
        }
    
        //UIPickerViewDelegate
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            if component  == 0 {
                return self.provincesData[row] as? String
            }else if component == 1 {
                return self.citiesData[row] as? String
            }else{
                return self.districtsData[row] as? String
            }
        }
    
    
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if component  == 0 {
                self.selectedProvince = self.provincesData[row] as! String
                self.citiesList = self.provincesList[selectedProvince] as! NSDictionary
                self.citiesData = citiesList.allKeys as NSArray
                self.selectedCity = self.citiesData[0] as! String
                self.districtsData = self.citiesList[selectedCity] as! NSArray
                self.selectedDistrict = self.districtsData[0] as! String
                self.addressPickView.reloadComponent(1)
                self.addressPickView.reloadComponent(2)
                NSLog("选择的省"+selectedProvince)
            }else if component == 1 {
                self.selectedCity = self.citiesData[row] as! String
                self.districtsData = self.citiesList[selectedCity] as! NSArray
                self.selectedDistrict = self.districtsData[0] as! String
                self.addressPickView.reloadComponent(2)
    
                NSLog("选择的市"+selectedCity)
            }else{
                self.selectedDistrict = self.districtsData[row] as! String
                NSLog("选择的区"+selectedDistrict)
            }
        }
    
    }
    
    

    【Download Source Code】

    http://download.csdn.net/detail/nc_jingjing/9788521

    【About me】

    qrcode_for_gh_b769b02099ba_258.jpg

    展开全文
  • Swift.地址选择器

    2018-11-08 09:21:27
    地址选择器:以省份,城市,地区三级进行选择,数据来自本地plist文件.有12个热门城市供快速选择,选择错误可以回选. 选择地区时进行将数据回调到上一控制器,点击页面空白区域退出controller. controller消失时:背景渐变...

    效果图

    实现效果:

    controller弹出时:半透明背景渐变展示.地址选择器从下方弹出.

    地址选择器:以省份,城市,地区三级进行选择,数据来自本地plist文件.有12个热门城市供快速选择,选择错误可以回选.

    选择地区时进行将数据回调到上一控制器,点击页面空白区域退出controller.

    controller消失时:背景渐变消失,地址选择器向下退出.

    #实现思路:
    本质上来说这是一个复杂版的日期选择器,有关弹出动画完全可以拿过来就用.

    所以主要复杂的点就是这个自定制的地址选择器.

    具体实现是写一个view其中包含tableView.给view三种type.来决定它当前的状态.然后根据type的改变来修改他的样式和数据展示,以及cell被点击时执行方法.

    实现方式:

    1.找到数据源,声明model将数据转成对象.

    2.实现地址选择器的样式,数据展示.

    3.实现我们需要的转场视图动画.

    4.将地址选择器加入一个ViewController,并修改其转场动画代理,使其使用自定制转场动画.

    5.实现地址选择器的功能,以及交互优化.


    1.找到数据源,声明model将数据转成对象.

    数据来自网络,一个plist文件.将其转换成model进行保存.

    struct EWCountryModel {
        var countryDictionary: Dictionary<String,EWProvincesModel> = [:]
        var provincesArray: [String] = []
        init(dic:Dictionary<String,Dictionary<String,Array<String>>>){
            for (key,value) in dic{
                let model = EWProvincesModel(dic: value)
                countryDictionary[key] = model
                provincesArray.append(key)
            }
        }
    }
    struct EWProvincesModel{
        var provincesDictionary: Dictionary<String,EWCityModel> = [:]
        var cityArray: [String] = []
        init(dic:Dictionary<String,Array<String>>){
            for (key,value) in dic{
                let model = EWCityModel(Arr: value)
                provincesDictionary[key] = model
                cityArray.append(key)
            }
        }
    }
    struct EWCityModel{
        var areaArray: Array<String> = []
        init(Arr:Array<String>){
            for str in Arr{
                areaArray.append(str)
            }
        }
    }
    
      /// 从area.plist获取全部地区数据
        func initLocationData(){
            let dic = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "area", ofType: "plist")!) as! Dictionary<String,Any>
            locationModel = EWCountryModel(dic: dic as! Dictionary<String, Dictionary<String, Array<String>>>)
            dataArray = locationModel?.provincesArray
        }
    

    2.实现地址选择器的样式,数据展示.

        func buildTitleScrollView() {
            if titleSV != nil {
                titleSV.removeFromSuperview()
            }
            buttonArr = []
            titleSV = UIScrollView(frame: CGRect(x: 0, y: 72, width: ScreenInfo.Width, height: 44))
            self.underLine = UIView(frame: CGRect(x: 0, y: 40, width: 30, height: 2))
            self.underLine.backgroundColor = UIColor.x4FB0FF
            for i in 0..<3{
                let button = UIButton(frame: CGRect(x: 24 + CGFloat(i) * (ScreenInfo.Width - 47) / 3, y: 0, width: ScreenInfo.Width / 3, height: 44))
                button.tag = Int(i)
                if i == 1 {
                    button.isSelected = true
                    underLine.center.x = button.center.x
                }
                button.setTitle("请选择", for: .normal)
                button.setTitleColor(UIColor.x333333, for: .normal)
                button.setTitleColor(UIColor.x4FB0FF, for: .selected)
                button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
                button.titleLabel?.adjustsFontSizeToFitWidth = true
                button.addTarget(self, action: #selector(onClickTitlebutton(sender:)), for: .touchUpInside)
                buttonArr.append(button)
                titleSV.addSubview(button)
            }
            titleSV.showsVerticalScrollIndicator = false
            titleSV.addSubview(self.underLine)
            titleSV.contentSize = CGSize(width: ScreenInfo.Width, height: 44)
            titleSV.isHidden = true
            self.addSubview(titleSV)
        }
        func drawTableView(){
            self.addSubview(tableView)
            tableView.delegate = self
            tableView.dataSource = self
            tableView.separatorStyle = .none
            tableView.tableHeaderView = tableViewHeaderView
            tableView.showsVerticalScrollIndicator = false
            tableView.register(EWAddressPickViewTableViewCell.self, forCellReuseIdentifier: EWAddressPickViewTableViewCell.identifier)
            tableView.register(EWAddressPickViewFirstTableViewCell.self, forCellReuseIdentifier: EWAddressPickViewFirstTableViewCell.identifier)
        }
    

    3.实现我们需要的转场视图动画.

           //EWAddressPickerViewController的推出和取消动画
    class EWAddressPickerPresentAnimated: NSObject,UIViewControllerAnimatedTransitioning {
    
        var type: EWAddressPickerPresentAnimateType = .present
    
        init(type: EWAddressPickerPresentAnimateType) {
            self.type = type
        }
        /// 动画时间
        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            return 0.3
        }
        /// 动画效果
        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    
            switch type {
            case .present:
                let toVC : EWAddressViewController = transitionContext.viewController(forKey: .to) as! EWAddressViewController
                let toView = toVC.view
    
                let containerView = transitionContext.containerView
                containerView.addSubview(toView!)
    
                toVC.containV.transform = CGAffineTransform(translationX: 0, y: (toVC.containV.frame.height))
    
                UIView.animate(withDuration: 0.25, animations: {
                    /// 背景变色
                    toVC.backgroundView.alpha = 1.0
                    /// addresspicker向上推出
                    toVC.containV.transform =  CGAffineTransform(translationX: 0, y: -10)
                }) { (finished) in
                    UIView.animate(withDuration: 0.2, animations: {
                        /// transform初始化
                        toVC.containV.transform = CGAffineTransform.identity
                    }, completion: { (finished) in
                        transitionContext.completeTransition(true)
                    })
                }
            case .dismiss:
                let toVC : EWAddressViewController = transitionContext.viewController(forKey: .from) as! EWAddressViewController
    
                UIView.animate(withDuration: 0.25, animations: {
                    toVC.backgroundView.alpha = 0.0
                    /// addresspicker向下推回
                    toVC.containV.transform =  CGAffineTransform(translationX: 0, y: (toVC.containV.frame.height))
                }) { (finished) in
                    transitionContext.completeTransition(true)
                }
            }
        }
    }
    
    

    4.将地址选择器加入一个ViewController,并修改其转场动画代理,使其使用自定制转场动画.

     lazy var containV: EWAddressPickView = {
            let view = EWAddressPickView(frame: CGRect(x: 0, y: ScreenInfo.Height-550, width: ScreenInfo.Width, height: 550))
            view.backOnClickCancel = {
                self.onClickCancel()
            }
            /// 成功选择后将数据回调,并推出视图
            view.backLocationString = { (address,province,city,area) in
                if self.backLocationStringController != nil{
                    self.backLocationStringController!(address,province,city,area)
                    self.onClickCancel()
                }
            }
            return view
        }()
    
    //MARK: - 转场动画delegate
    extension EWAddressViewController:UIViewControllerTransitioningDelegate{
        /// 推入动画
        func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let animated = EWAddressPickerPresentAnimated(type: .present)
            return animated
        }
        /// 推出动画
        func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let animated = EWAddressPickerPresentAnimated(type: .dismiss)
            return animated
        }
    }
    

    5.实现地址选择器的功能,以及交互优化.

    主要复杂的部分,只能展示其中一部分代码,具体实现还是要在demo中看.

     private var tableViewType: EWLocationPickViewTableViewType = .provinces{
            didSet{
                switch tableViewType {
                case .provinces:
                    /// 选择省份时,有上面的热门城市view.没有滚动选择type的titleScrollView.没有已选择label.
                    self.tableView.tableHeaderView = tableViewHeaderView
                    self.tableView.frame = CGRect(x: 0, y: 42, width: ScreenInfo.Width, height: 458)
                    self.titleSV.isHidden = true
                    self.leftLabel.isHidden = true
                    /// 将所有选中数据清空
                    self.provincesModel = nil
                    self.selectedProvince = ""
                    self.selectedCity = ""
                    self.selectedArea = ""
                    self.cityModel = nil
                    // 将titleSV中所有button的title重置
                    // 并将第一个button设置为选中状态,已保证选择城市后button下的横线有滚动效果.
                    for button in buttonArr {
                        button.setTitle("请选择", for: .normal)
                        button.isSelected = false
                        if button.tag == 0{
                            button.isSelected = true
                        }
                    }
                    self.underLine.center = CGPoint(x: self.buttonArr[1].center.x, y: self.underLine.center.y)
                    self.dataArray = locationModel?.provincesArray
                    self.tableView.reloadData()
                case .city:
                    /// 选择城市时没有热门城市view,并将titleSV显示出来
                    self.tableView.tableHeaderView = UIView()
                    self.tableView.frame = CGRect(x: 0, y: 136, width: ScreenInfo.Width, height: 367)
                    self.titleSV.isHidden = false
                    self.leftLabel.isHidden = false
                    /// 将省份选择保留,将城市与地区数据清空
                    self.selectedCity = ""
                    self.selectedArea = ""
                    self.cityModel = nil
                    /// 通过修改titleSV中button的选中状态来修改它的颜色
                    for button in buttonArr {
                        button.isSelected = false
                        if button.tag != 0{
                            button.setTitle("请选择", for: .normal)
                        }
                        if button.tag == 1{
                            button.isSelected = true
                        }
                    }
    
                    /// 滚动titleSV中button下滚动的Line
                    UIView.animate(withDuration: 0.3, animations: {() -> Void in
                        self.underLine.center = CGPoint(x: self.buttonArr[1].center.x, y: self.underLine.center.y)
                    })
    
                    self.dataArray = provincesModel?.cityArray
                    self.tableView.reloadData()
                case .area:
                    /// 选择地区时没有上方热门城市View,有titleSV
                    self.tableView.tableHeaderView = UIView()
                    self.tableView.frame = CGRect(x: 0, y: 136, width: ScreenInfo.Width, height: 367)
                    self.titleSV.isHidden = false
                    self.leftLabel.isHidden = false
                    /// 通过修改titleSV中button的选中状态来修改它的颜色
                    for button in buttonArr {
                        button.isSelected = false
                        if button.tag == 2{
                            button.isSelected = true
                        }
                    }
                    /// 滚动titleSV中button下滚动的Line
                    UIView.animate(withDuration: 0.3, animations: {() -> Void in
                        self.underLine.center = CGPoint(x: self.buttonArr[2].center.x, y: self.underLine.center.y)
                    })
                    self.dataArray = cityModel?.areaArray
                    self.tableView.reloadData()
                }
            }
        }
    

    使用方法:

    将EWAddressPicker文件夹拖入项目,调用时:

    let addressPicker = EWAddressViewController()
    /*** 可使用这种init方法自定制选中颜色,不填写selectColor默认颜色为UIColor(red: 79/255, green: 176/255, blue: 255/255, alpha: 1),蓝色
    let addressPicker = EWAddressViewController(selectColor: UIColor.yellow)
    */
    // 返回选择数据,地址,省,市,区
    addressPicker.backLocationStringController = { (address,province,city,area) in
        self.label.text = address
    }
    self.present(addressPicker, animated: true, completion: nil)
    

    demo地址:AddressPicker

    OC版本:OC.地址选择器.

    有问题欢迎探讨.

    展开全文
  • swift版本日期时间选择器
  • 之前的地址选择器都是网上找的,但是网上的第三方,功能很多,看起来还要配置不少东西.用起来麻烦. 然后,我就自己写了一个.只有地址选择功能,连数据源都自己搞好…方便很多.后来想想不知道,有没有人也像我一样只是想到...

    AreaPickerView_swift

    areapicker in china, easy to use. 中国的地区选择器.简单易用.

    之前的地址选择器都是网上找的,但是网上的第三方,功能很多,看起来还要配置不少东西.用起来麻烦. 然后,我就自己写了一个.只有地址选择功能,连数据源都自己搞好…方便很多.后来想想不知道,有没有人也像我一样只是想到一个简单的地区选择器而已.然后,我就上传上github上面了….. 希望有人能看到吧…
    直接继承自UIpickerView.

    AreaPaickerView

    AreaPickerView

    只需要实现三个代理方法

    internal func cancel(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
    //还原原来的值……
    }

    internal func sure(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
    //设置新值
    }

    internal func statusChanged(areaPickerView: AreaPickerView, pickerView: UIPickerView, textField: UITextField, locate: Location) {
    //立即显示新值
    }

    展开全文
  • IGColorPicker 一个采用Swift编写的iOS自定义颜色选择器
  • LwDatePicker时间选择器
  • Swift.日期选择器

    2018-11-07 09:14:37
    时间选择器从下方弹出.选择器日期滚动到当前日期. 点击确认进行将数据回调到上一控制器,点击页面空白区域退出controller. controller消失时:背景渐变消失,时间选择器向下退出. 实现方式: 1.首先写一个ViewController...

    效果图

    实现效果:

    controller弹出时:半透明背景渐变展示.时间选择器从下方弹出.选择器日期滚动到当前日期.

    点击确认进行将数据回调到上一控制器,点击页面空白区域退出controller.

    controller消失时:背景渐变消失,时间选择器向下退出.

    实现方式:

    1.首先写一个ViewController,将DatePicker加入.

    2.实现DatePicker的展示效果与功能.

    3.修改viewController的背景色,使其半透明.

    4.实现我们需要的转场视图动画.

    5.修改ViewController的transitioningDelegate,使其使用我们重写的转场视图动画.


    1.首先写一个ViewController,将DatePicker加入.

            let cancel = UIButton(frame: CGRect(x: 0, y: 10, width: 70, height: 20))
            let sure = UIButton(frame: CGRect(x: ScreenInfo.Width - 80, y: 10, width: 70, height: 20))
            cancel.setTitle("取消", for: .normal)
            sure.setTitle("确认", for: .normal)
            cancel.setTitleColor(UIColor.colorWithRGBA(r: 255, g: 51, b: 102, a: 1), for: .normal)
            sure.setTitleColor(UIColor.colorWithRGBA(r: 255, g: 51, b: 102, a: 1), for: .normal)
            cancel.addTarget(self, action: #selector(self.onClickCancel), for: .touchUpInside)
            sure.addTarget(self, action: #selector(self.onClickSure), for: .touchUpInside)
            picker = UIPickerView(frame: CGRect(x: 0, y: 24, width: ScreenInfo.Width, height: 216))
            picker.delegate = self
            picker.dataSource = self
            picker.backgroundColor = UIColor.clear
            picker.clipsToBounds = true//如果子视图的范围超出了父视图的边界,那么超出的部分就会被裁剪掉。
            //创建日期选择器
            self.containV.addSubview(cancel)
            self.containV.addSubview(sure)
            self.containV.addSubview(picker)
            self.view.addSubview(self.containV)
    

    2.实现DatePicker的展示效果与功能.

      //MARK: - PickerViewDelegate
    extension EWDatePickerViewController:UIPickerViewDelegate,UIPickerViewDataSource {
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 3
        }
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            if component == 0 {
                return 10
            }else if component == 1 {
                return 12
            }else {
                let year: Int = pickerView.selectedRow(inComponent: 0) + currentDateCom.year!
                let month: Int = pickerView.selectedRow(inComponent: 1) + 1
                let days: Int = howManyDays(inThisYear: year, withMonth: month)
                return days
            }
        }
        private func howManyDays(inThisYear year: Int, withMonth month: Int) -> Int {
            if (month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12) {
                return 31
            }
            if (month == 4) || (month == 6) || (month == 9) || (month == 11) {
                return 30
            }
            if (year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3) {
                return 28
            }
            if year % 400 == 0 {
                return 29
            }
            if year % 100 == 0 {
                return 28
            }
            return 29
        }
        func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
            return ScreenInfo.Width / 3
        }
        func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
            return 40
        }
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            if component == 0 {
                return "\((currentDateCom.year!) + row)\("年")"
            }else if component == 1 {
                return "\(row + 1)\("月")"
            }else {
                return "\(row + 1)\("日")"
            }
        }
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if component == 1 {
                pickerView.reloadComponent(2)
            }
        }
    }
    

    3.修改viewController的背景色,使其半透明.

            var backgroundView:UIView = {
                let view = UIView()
                view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
                return view
            }()
            self.view.backgroundColor = UIColor.clear
            self.view.insertSubview(self.backgroundView, at: 0)
            self.modalPresentationStyle = .custom//viewcontroller弹出后之前控制器页面不隐藏 .custom代表自定义
    

    4.实现我们需要的转场视图动画.

       //EWDatePickerViewController的推出和取消动画
    class EWDatePickerPresentAnimated: NSObject,UIViewControllerAnimatedTransitioning {
    
        var type: EWDatePickerPresentAnimateType = .present
    
        init(type: EWDatePickerPresentAnimateType) {
            self.type = type
        }
        /// 动画时间
        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            return 0.3
        }
        /// 动画效果
        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    
            switch type {
            case .present:
                let toVC : EWDatePickerViewController = transitionContext.viewController(forKey: .to) as! EWDatePickerViewController
                let toView = toVC.view
    
                let containerView = transitionContext.containerView
                containerView.addSubview(toView!)
    
                toVC.containV.transform = CGAffineTransform(translationX: 0, y: (toVC.containV.frame.height))
    
                UIView.animate(withDuration: 0.25, animations: {
                    /// 背景变色
                    toVC.backgroundView.alpha = 1.0
                    /// datepicker向上推出
                    toVC.containV.transform =  CGAffineTransform(translationX: 0, y: -10)
                }) { (finished) in
                    UIView.animate(withDuration: 0.2, animations: {
                        /// transform初始化
                        toVC.containV.transform = CGAffineTransform.identity
                    }, completion: { (finished) in
                        transitionContext.completeTransition(true)
                    })
                }
            case .dismiss:
                let toVC : EWDatePickerViewController = transitionContext.viewController(forKey: .from) as! EWDatePickerViewController
    
                UIView.animate(withDuration: 0.25, animations: {
                    toVC.backgroundView.alpha = 0.0
                    /// datepicker向下推回
                    toVC.containV.transform =  CGAffineTransform(translationX: 0, y: (toVC.containV.frame.height))
                }) { (finished) in
                    transitionContext.completeTransition(true)
                }
            }
        }
    }
    

    5.修改ViewController的transitioningDelegate,使其使用我们重写的转场视图动画.

    //MARK: - 转场动画delegate
    extension EWDatePickerViewController:UIViewControllerTransitioningDelegate{
        func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let animated = EWDatePickerPresentAnimated(type: .present)
            return animated
        }
        func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let animated = EWDatePickerPresentAnimated(type: .dismiss)
            return animated
        }
    }
    

    demo地址:DatePicker.求star.

    有问题欢迎探讨.

    展开全文
  • swift 三级可选的下拉菜单选择器
  • 省市区选择器,省市二级选择,省市区三级选择,PickView
  • 自定义选择器:包括满足城市选择和单列选择
  • 滚动选择器.swift
  • Swift基础之PickerView(时间)选择器

    千次阅读 2016-08-02 11:01:55
    代码讲解:(后面有额外代码讲解) 首页设计UIPickerView的样式设计: leftArray = ["花朵","颜色","形状"];   ... let array1 = ["茉莉","玫瑰","郁金香","紫罗兰"];... let array2 = ["红色","黄色","黑色","白色...
  • github:https://github.com/fengzhihao123/UI-Swift 如果对您有所帮助,还请点个star支持一下!
  • 2,第二个场景包含一个日期选择器,一个关闭视图按钮。 设计界面如下图所示: 初始场景: 第二场景:   1,拖一个工具栏控件到storyboard 2, 修改默认Item文本为"选择一
  • Swift4.2编写的分段选择器
  • 城市选择器(包含子级别全部地区的选择)
  • PCDatePicker 五级时间选择器(年月日时分)
  • 相册、照片选择器(多选、单选)
  • swift-时间选择器View

    2020-07-30 23:33:17
    时间选择器View
  • Swift简单的颜色选择器和SwiftMessage提示框 简单的颜色选择器为 KKColorListPicker 方法简单 先导入KKColorListViewControllerDelegate var viewColor:KKColorListViewController! viewColor = ...
1 2 3 4 5 ... 20
收藏数 18,739
精华内容 7,495
关键字:

地址选择器swift