iOS之UIPickview (二)省市区联动

2024-05-31 10:32

本文主要是介绍iOS之UIPickview (二)省市区联动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

=======省市二级联动=====

 

#import <Foundation/Foundation.h>

 

@interface CZProvince : NSObject

 

/** 省的名称 */

@property (nonatomic,copy) NSString *name;

 

/** 对应的城市数据 */

@property (nonatomic,strong) NSArray *cities;

 

+ (instancetype)provinceWithDict:(NSDictionary *)dict;

 

- (instancetype)initWithDict:(NSDictionary *)dict;

 

 

@end

*********************************

#import "CZProvince.h"

 

@implementation CZProvince

 

- (instancetype)initWithDict:(NSDictionary *)dict

{

    self = [superinit];

    if (self) {

        [selfsetValuesForKeysWithDictionary:dict];

    }

    returnself;

}

 

+ (instancetype)provinceWithDict:(NSDictionary *)dict {

 

    return [[selfalloc] initWithDict:dict];

}

**************************

 

#import <UIKit/UIKit.h>

 

@interface ViewController : UIViewController

 

 

@end

 

 

 

 

*****************

 

#import "ViewController.h"

#import "CZProvince.h"

 

@interface ViewController () <UIPickerViewDelegate,UIPickerViewDataSource>

 

 

@property (weak,nonatomic) IBOutletUIPickerView *pickerView;

@property (weak,nonatomic) IBOutletUILabel *provinceLbl;

@property (weak,nonatomic) IBOutletUILabel *cityLbl;

 

 

 

 

// 省模型的数组

@property (nonatomic,strong) NSArray *provinces;

 

// 保存上一次显示或选中的省

@property (nonatomic,strong) CZProvince *selPro;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [superviewDidLoad];

 

    // 设置数据源.代理对象

    self.pickerView.dataSource =self;

    self.pickerView.delegate =self;

    

    // 设置默认的选中

    [selfpickerView:self.pickerViewdidSelectRow:0 inComponent:0];

}

 

 

#pragma mark - 代理方法

//在label上显示

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    

    // 如果滚动的是第0列,要刷新第1列城市数据

    if (component == 0) {

        [pickerView reloadComponent:1];

        // 选中第1列第0行

        [pickerView selectRow:0inComponent:1 animated:YES];

    }

 

    // 获取省的名称获取市的名称

    // 得获取pickerView第0列的选中行第1列的选中行

    NSInteger selProIdx = [pickerViewselectedRowInComponent:0];

    NSInteger selCityIdx = [pickerViewselectedRowInComponent:1];

    

    // 设置省

    CZProvince *selPro =self.provinces[selProIdx];

    self.provinceLbl.text = selPro.name;

    

    // 设置市

//    self.cityLbl.text = selPro.cities[selCityIdx];

    self.cityLbl.text =self.selPro.cities[selCityIdx];//注意用保存的省得模型去赋值

    

}

 

// 返回显示的内容

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    

    NSLog(@"titleForRow");

    

    // 如果是第0列,直接返回省的名称

    if (component == 0) {

        CZProvince *pro =self.provinces[row];

        return pro.name;

    } else {

    

//        // 如果是第1列,根据省确定市的数据

//        NSInteger selProIdx = [pickerView selectedRowInComponent:0];

//        CZProvince *selPro = self.provinces[selProIdx];//获取省得模型

//        

//        // 城市的数组

//        NSArray *cities = selPro.cities;

//        

//        // 返回内容

//        return cities[row];

        

        returnself.selPro.cities[row];

        

    }

}

 

 

#pragma mark - 数据源方法

// 返回组的数量

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {

 

    return 2;

}

 

// 返回每一组有多少行

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

 

    // 如果是第0列,行数就是模型数量

    if (component == 0) {

        returnself.provinces.count;

    } else {

 

        // 如果是第1列,根据第0列的省确定城市的数量

        // 1. 获取第0列选中下标

        NSInteger selProIdx = [pickerViewselectedRowInComponent:0];

        

        // 2. 根据下标去获取省模型

        CZProvince *selPro =self.provinces[selProIdx];

        

        

        // 保存选中的省模型

        self.selPro = selPro;

        

        returnself.selPro.cities.count;

    

        

//        // 3. 到模型中获取城市数量

//        return selPro.cities.count;

    

    }

}

 

 

#pragma mark - 懒加载

- (NSArray *)provinces {

 

    if (_provinces ==nil) {

        

        // 获取文件路径转为字典数组

        NSArray *dictArr = [NSArrayarrayWithContentsOfFile:[[NSBundlemainBundle] pathForResource:@"02cities.plist"ofType:nil]];

        

        // 遍历数组转为模型数组

//        for (<#initialization#>; <#condition#>; <#increment#>) {

//            <#statements#>

//        }

 

//        for (<#type *object#> in <#collection#>) {

//            <#statements#>

//        }

//        for (id obj in dictArr) {

//            NSDictionary *dict = (NSDictionary *)obj;

//            CZProvince *pro = [CZProvince provinceWithDict:dict];

//        }

        

        // 通过block遍历

        // 临时数组保存所有的模型

        NSMutableArray *tempArrM = [NSMutableArrayarrayWithCapacity:dictArr.count];

        [dictArr enumerateObjectsUsingBlock:^(NSDictionary *_Nonnull obj,NSUInteger idx, BOOL *_Nonnull stop) {

            

            CZProvince *province = [CZProvinceprovinceWithDict:obj];

            [tempArrM addObject:province];

            

        }];

        

        _provinces = tempArrM;

        

    }

 

    return_provinces;

}

 

 

=======================省市区三级联动======================

//省市模型#import <Foundation/Foundation.h>@interface LYProvinceModel : NSObject
@property(nonatomic,copy)NSString *state;//省直辖市名
@property(nonatomic,strong)NSArray *cities;//城市数组
@end********
#import "LYProvinceModel.h"
#import "MJExtension.h"
#import "LYHomeCityModal.h"
@implementation LYProvinceModel
+ (NSDictionary *)objectClassInArray
{return @{@"cities" : [LYHomeCityModal class]};}
@end*********
//市模型#import <Foundation/Foundation.h>@interface LYHomeCityModal : NSObject
@property(nonatomic,copy)NSString *city;//城市名
@property(nonatomic,strong)NSArray *areas;//县区的数组
@end*******
#import "LYHomeCityModal.h"@implementation LYHomeCityModal@end********
/**省市区三级联动使用:LYBPickviewWithProvinceAndCityAndareaView *provinceAndCityAndArea=[[LYBPickviewWithProvinceAndCityAndareaView alloc]initWithFrame:CGRectMake(0, HEIGHT/2, WIDTH, HEIGHT/2)];//选择省市区后的回调[provinceAndCityAndArea setSelectProvinceAndCityAndAreaBlock:^(NSString * _Nonnull province, NSString * _Nonnull city, NSString * _Nonnull area) {NSLog(@"省---%@,市---%@,区---%@",province,city,area);}];[self.view addSubview:provinceAndCityAndArea];*/
#import <UIKit/UIKit.h>NS_ASSUME_NONNULL_BEGIN@interface LYBPickviewWithProvinceAndCityAndareaView : UIView
/**选中省市区后的回调*/
@property(nonatomic,copy)void (^selectProvinceAndCityAndAreaBlock)(NSString *province,NSString *city,NSString *area);
@endNS_ASSUME_NONNULL_END*********
/**省市区三级联动*/#import "LYBPickviewWithProvinceAndCityAndareaView.h"
#import "LYHomeCityModal.h"
#import "LYProvinceModel.h"
#import "MJExtension.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface LYBPickviewWithProvinceAndCityAndareaView()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic,strong)LYProvinceModel *provinceModal;
@property(nonatomic,strong) LYHomeCityModal *citymodal;
@property(nonatomic,strong)UIPickerView *pickview;
@property(nonatomic,strong)NSArray *provinceArr;//模型数组
@property(nonatomic,strong)UIView *bgv;
@property(nonatomic,copy)NSString *selectProvince;//选中的省
@property(nonatomic,copy)NSString *selectCity;// 选中的地级市
@property(nonatomic,copy)NSString *selectArea;//选中的区县
@end
@implementation LYBPickviewWithProvinceAndCityAndareaView
-(instancetype)initWithFrame:(CGRect)frame{if(self=[super initWithFrame:frame]){[self surePronvinceAndCityAndZoneWithFrame:frame];}return self;
}-(NSArray *)provinceArr{if(nil==_provinceArr){_provinceArr=[[NSArray alloc]init];}return _provinceArr;
}
//解析plist文件
-(void)parsePlistFile{//        NSString *path=[[NSBundle mainBundle]pathForResource:@"shengshiquxianarea.plist" ofType:nil];//        NSArray *arr=[NSArray arrayWithContentsOfFile:path];//    NSLog(@"plist---arr---%@",arr);NSArray *modalArr=[LYProvinceModel mj_objectArrayWithFilename:@"shengshiquxianarea.plist"];//字典转模型self.provinceArr=modalArr;}
//确定省市区编码
-(void)surePronvinceAndCityAndZoneWithFrame:(CGRect)frame{[self parsePlistFile];//解析plist文件if(self.provinceArr &&[self.provinceArr count]>0){if(!self.bgv){self.bgv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/2)];//}self.bgv.backgroundColor=[UIColor colorWithWhite:0.9 alpha:1];[self addSubview:self.bgv];UIPickerView *pickview=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, HEIGHT/2-30)];pickview.backgroundColor=[UIColor colorWithWhite:0.9 alpha:1];[self.bgv addSubview:pickview];pickview.delegate=self;pickview.dataSource=self;self.pickview=pickview;UIButton *cancelbtn=[[UIButton alloc]initWithFrame:CGRectMake(WIDTH-140, 0, 60, 30)];[cancelbtn setTitleColor:[UIColor colorWithRed:39.0/255 green:131.0/255 blue:207.0/255 alpha:1] forState:UIControlStateNormal];[cancelbtn setTitle:@"取消" forState:UIControlStateNormal];[self.bgv addSubview:cancelbtn];[cancelbtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchDown];UIButton *surebtn=[[UIButton alloc]initWithFrame:CGRectMake(WIDTH-70, 0, 60, 30)];[surebtn setTitle:@"确定" forState:UIControlStateNormal];[self.bgv addSubview:surebtn];[surebtn setTitleColor:[UIColor colorWithRed:39.0/255 green:131.0/255 blue:207.0/255 alpha:1] forState:UIControlStateNormal];[surebtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchDown];// 设置默认的选中[self pickerView:self.pickview didSelectRow:0 inComponent:0];//获取默认的省市区if(self.provinceArr.count>0){LYProvinceModel *provincemodel=self.provinceArr[0];self.selectProvince=provincemodel.state;if(provincemodel.cities.count>0){LYHomeCityModal *cityMode=provincemodel.cities[0];self.selectCity=cityMode.city;NSArray *areas=cityMode.areas;if(areas.count>0){self.selectArea=areas[0];}else {self.selectArea=@"";}}else{self.selectCity=@"";}}}
}-(void)cancelClick{NSLog(@"点击执行");CGRect frame=self.bgv.frame;frame.origin.y=HEIGHT;self.bgv.frame=frame;self.bgv.alpha=0;
}
-(void)sureClick{CGRect frame=self.bgv.frame;frame.origin.y=HEIGHT;self.bgv.frame=frame;self.bgv.alpha=0;//调用block吧省市区传给调用的页面
self.selectProvinceAndCityAndAreaBlock(self.selectProvince?self.selectProvince:@"", self.selectCity?self.selectCity:@"", self.selectArea?self.selectArea:@"");
}
#pragma mark - 代理方法
//选中一行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {if(self.provinceArr && [self.provinceArr count]>0){if(component==0){NSInteger provincenum = [pickerView selectedRowInComponent:0];//第1列选中的行--省LYProvinceModel *provincemodal  =self.provinceArr[provincenum];self.provinceModal=provincemodal;self.selectProvince=provincemodal.state;//选中的省名if(provincemodal.cities.count>0){LYHomeCityModal *cityMode=provincemodal.cities[0];self.selectCity=cityMode.city;//选中的地级市名NSArray *areas=cityMode.areas;if(areas.count>0){self.selectArea=areas[0];//选中的区县名}else {self.selectArea=@"";}}// 如果滚动的是第0列,要刷新第1列城市数据[pickerView reloadComponent:1];// 选中第1列第0行[pickerView selectRow:0 inComponent:1 animated:YES];if(self.provinceModal.cities[0]){//选择省的时候刷新完市,再刷新区// 如果滚动的是第1列,要刷新第2列城市数据[pickerView reloadComponent:2];// 选中第2列第0行[pickerView selectRow:0 inComponent:2 animated:YES];}}else if(component==1){LYProvinceModel *provincemodal=self.provinceModal;NSInteger citynum = [pickerView selectedRowInComponent:1];//第2列选中的行--市LYHomeCityModal *citymodal=provincemodal.cities[citynum];self.selectCity=citymodal.city;//选中的城市名NSArray *areas=citymodal.areas;if(areas.count>0){self.selectArea=areas[0];//选中的区县名}else {self.selectArea=@"";}if(citymodal.areas.count!=0){//如果第三列有数据才刷新// 如果滚动的是第1列,要刷新第2列城市数据[pickerView reloadComponent:2];// 选中第2列第0行[pickerView selectRow:0 inComponent:2 animated:YES];}}else if(component==2){NSInteger zonenum = [pickerView selectedRowInComponent:2];//第3列选中的行--区LYHomeCityModal *citymodal=self.citymodal;if(citymodal.areas.count>zonenum){self.selectArea=citymodal.areas[zonenum];//选中的区县}}}
}//-返回每一行的内容自定义的显示,可以自己设置字体大小字体颜色
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{UIView *v=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH/3-20,30)];UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(20, 0, WIDTH/3-20,30)];[v addSubview:lbl];lbl.font=[UIFont systemFontOfSize:15];if(component==0){LYProvinceModel *provinceModal=self.provinceArr[row];lbl.text=provinceModal.state;}else if(component==1){LYProvinceModel *provinceModal=self.provinceModal;LYHomeCityModal *citymodal=provinceModal.cities[row];lbl.text=citymodal.city;}else if(component==2){LYHomeCityModal *citymodal=self.citymodal;lbl.text=citymodal.areas[row];}return v;
}#pragma mark - 数据源方法
// 返回有多少列"组"
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {return 3;}// 返回每一组有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {if(component==0){//省return self.provinceArr.count;}else if(component==1){//市NSInteger provincenum = [pickerView selectedRowInComponent:0];//第1列选中的行// 2. 根据下标去获取省模型LYProvinceModel *provinceModal = self.provinceArr[provincenum];self.provinceModal=provinceModal;//保存选中的省模型return provinceModal.cities.count;}else if(component==2){//区NSInteger citynum = [pickerView selectedRowInComponent:1];//第2列选中的行
//        NSLog(@"--区---%tu",citynum);LYProvinceModel *provinceModal=self.provinceModal;LYHomeCityModal *citymodal=provinceModal.cities[citynum];//选中的市模型self.citymodal=citymodal;//保存市模型NSArray *zoneArr=citymodal.areas;
//        NSLog(@"--zonearr--%tu",zoneArr.count);return zoneArr.count;}// 返回行数return 10;
}返回每一行显示的内容---用了上面自定义的view,这里系统的方法注释掉了
//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//    if(component==0){
//     LYHomeProvinceModal *provinceModal=self.provinceArr[row];
//    return provinceModal.state;
//
//    }else if(component==1){
//        LYHomeProvinceModal *provinceModal=self.provinceModal;
//        LYHomeCityModal *citymodal=provinceModal.cities[row];
//        return citymodal.city;
//
//    }else if(component==2){
//
//        LYHomeCityModal *citymodal=self.citymodal;
//        return citymodal.areas[row];
//    }
//    return @"安徽";
//}
@end

 

这篇关于iOS之UIPickview (二)省市区联动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1017752

相关文章

iOS HTTPS证书不受信任解决办法

之前开发App的时候服务端使用的是自签名的证书,导致iOS开发过程中调用HTTPS接口时,证书不被信任 - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAu

vue+elementUI下拉框联动显示

<el-row><el-col :span="12"><el-form-item label="主账号:" prop="partyAccountId" :rules="[ { required: true, message: '主账号不能为空'}]"><el-select v-model="detailForm.partyAccountId" filterable placeholder="

IOS 数组去重的几种方式

本来只知道NSSet和KeyValues的。今天又新学了几种方式 还有就是和同事学的一种方式 外层循环从0开始遍历,内层从最后一个元素开始遍历 for(int i=0;i<index;i++){  for(int j=index-1;j>i;j-- ){ } }

iOS Assertion failure in -[UITableView _classicHeightForRowAtIndexPath:]

iOS Assertion failure in -[UITableView _classicHeightForRowAtIndexPath:]  2015-04-24 11:40  956人阅读  评论(0)  收藏  举报   分类:   iOS 基础篇(208)  版权声明:本文为博主原创文章,未经博主允许不得转载。 Assertion

iOS:编译时出现no such file or directory:xxx以及use twice...filenames are used to distinguish private dec

简    注册  登录   添加关注 作者  婉卿容若 2016.04.29 11:22 写了21870字,被16人关注,获得了14个喜欢 iOS:编译时出现"no such file or directory:xxx"以及"use twice...filenames are used to distinguish private

iOS 到处 ipa包的时候 会有四个选项分别代表什么

如图 在 iOS 到处 ipa包的时候 会有四个选项  1.Save for iOS App Store Deployment 保存到本地 准备上传App Store 或者在越狱的iOS设备上使用 2.Save for Ad Hoc Deployment 保存到本地 准备在账号添加的可使用设备上使用(具体为在开发者账户下添加可用设备的udid),该app包是发布证书编

iOS 7适配上存在的各种问题

谈谈项目中遇到的各种iOS7适配问题 由于我的项目要适配到iOS7.1, 而现在已经是9时代了,在实际工作中我也是遇到了各种奇葩的坑,所以我想尽快把遇到的iOS7适配问题和解决方案分享出来,以后这些东西可能就用处不大了。   1.字体问题 iOS7中的字体适配恐怕是最麻烦的坑了,原因是iOS7以上的许多字体在7都是不存在的,甚至包括一些system-字体。比如system-

潜艇伟伟迷杂交版植物大战僵尸2024最新免费安卓+ios苹果+iPad分享

嗨,亲爱的游戏迷们!今天我要给你们种草一个超有趣的游戏——植物大战僵尸杂交版。这款游戏不仅继承了原有经典游戏的核心玩法,还加入了许多创新元素,让玩家能够体验到前所未有的乐趣。快来跟随我一起探索这个神奇的世界吧! 植物大战僵尸杂交版最新绿色版下载链接: https://pan.quark.cn/s/d60ed6e4791c 🔥 创新与经典的完美结合 植物大战僵尸杂交版在保持了原游戏经典玩

浏览器在iOS或Android中的一些方法

判断当前应用 var deviceType="H5"if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {deviceType='ios'} else if (/(Android)/i.test(navigator.userAgent)) {// alert("Android");deviceType='android'} else

iOS 视图之间的各种传值方式

属性传值 将A页面所拥有的信息通过属性传递到B页面使用 B页面定义了一个naviTitle属性,在A页面中直接通过属性赋值将A页面中的值传到B页面。 A页面DetailViewController.h文件 #import <UIKit/UIKit.h> #import "DetailViewController.h" @interface RootViewCon