前幾天寫項目遇到選擇數據的狀況,因此封裝了一下三種選擇器(單行數據選擇,日期選擇,城市選擇),都以AlterController的方式Model到控制器,原理是和PickerView是同樣的,城市選擇涉及到了三級聯動,同時也寫了三級聯動中數組越界的問題(固然若是使用模型的話,更容易避免). 歡迎有興趣的同窗能夠聯繫我郵箱liuqinghe66@gmail.com與我討論git
Github.Demo地址 : github.com/TynnPassBy/…github
下載後拖入項目,導入一個頭文件便可:json
#import "AlterController.h"
複製代碼
1.建立須要彈出的AlterController數組
AlterController *pickerView = [[AlterController alloc]initWithTitle:@"選擇單行數據" type:kTypeOfSingleLine];
//設置數據
pickerView.dataArray = @[@"波多野結衣",@"天海翼",@"小澤瑪利亞",@"大橋未久"];
//設置代理
pickerView.delegate = self;
[self presentViewController:pickerView animated:YES completion:nil];
//selectedBtn是一個定義的屬性,用於標記你所點擊的按鈕是哪一個
self.selectedBtn = sender;
複製代碼
2.實現代理方法bash
-(void)getResultFromPickView:(NSString *)result{
[self.selectedBtn setTitle:result forState:UIControlStateNormal];
}
複製代碼
提示:ui
1.建立須要彈出的AlterControllerspa
AlterController *pickerView = [[AlterController alloc]initWithTitle:@"選擇日期" type:kTypeOfDate];
pickerView.dataArray = [self getDateData];
pickerView.delegate = self;
[self presentViewController:pickerView animated:YES completion:nil];
//標記所選按鈕
self.selectedBtn = sender;
複製代碼
2.加載日期數據代理
//獲取日期數據
- (NSArray *)getDateData{
NSInteger year = 1900;
NSMutableArray *yearArray = [NSMutableArray array];
for (NSInteger i = 0; i<130; i++) {
NSString *newYear = [NSString stringWithFormat:@"%zd",year + i];
[yearArray addObject:newYear];
}
NSInteger month = 0;
NSMutableArray *monthArray = [NSMutableArray array];
for (NSInteger i = 0; i<12; i++) {
NSString *newMonth = [NSString stringWithFormat:@"%zd",month + i + 1];
[monthArray addObject:newMonth];
}
NSMutableArray *totalArray = [NSMutableArray array];
[totalArray addObject:yearArray];
[totalArray addObject:monthArray];
return totalArray;
}
複製代碼
3.實現代理方法code
-(void)getResultFromPickView:(NSString *)result{
[self.selectedBtn setTitle:result forState:UIControlStateNormal];
}
複製代碼
1.建立須要彈出的AlterControllerorm
AlterController *pickerView = [[AlterController alloc]initWithTitle:@"選擇城市" type:kTypeOfCity];
pickerView.dataArray = [self getCityData];
pickerView.delegate = self;
[self presentViewController:pickerView animated:YES completion:nil];
//標記所選按鈕
self.selectedBtn = sender;
複製代碼
2.加載城市數據
//獲取json中的城市數據
- (NSArray *)getCityData{
//province.json文件在demo中有,若是須要的話請你們下載demo哈,若是使用其餘json或者XML文件可能出現顯示數據錯誤哦
NSString* path = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
NSString* cityNames = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
if (cityNames == nil) {
NSLog(@"error:加載城市數據爲空");
return nil;
}
NSData *jsonData = [cityNames dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSArray *arrayCityNames = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失敗:%@",err);
return nil;
}
return arrayCityNames;
}
複製代碼
3.實現代理方法
-(void)getResultFromPickView:(NSString *)result{
[self.selectedBtn setTitle:result forState:UIControlStateNormal];
}
複製代碼