最近点楼,上課講解了日期選擇器和普通數(shù)據(jù)選擇器的使用,上課講解的案例是假期學(xué)生去向登記悴品,該項目有一定的實際意義禀综,可以在后期的教學(xué)中不斷的有話,并和數(shù)據(jù)庫老師去協(xié)調(diào)一些苔严,能不能數(shù)據(jù)庫中解決一下數(shù)據(jù)的問題定枷,當(dāng)然這部分知識現(xiàn)在暫時還不需要。
目前届氢,我的課堂教學(xué)上已經(jīng)完成了離校日期欠窒、返校日期、地域選擇等內(nèi)容的輸入設(shè)計悼沈,前面兩個難度不大贱迟,地域選擇的處理上姐扮,對于初學(xué)者有如下問題要解決:
1絮供、解析plist文件;
2茶敏、加載數(shù)據(jù)到數(shù)據(jù)選擇控件壤靶,使用PickerView控件的屬性和方法:(1)使用何種協(xié)議;(2)數(shù)據(jù)源屬性和代理屬性惊搏;(3)設(shè)置組件的個數(shù)(4)返回某列數(shù)據(jù)的行數(shù)(5)設(shè)置每行的文本顯示(6)數(shù)據(jù)聯(lián)動
3.在實現(xiàn)(4)贮乳、(5)的功能時提煉一個loadData方法
程序的源碼如下:
//
//ViewController.m
//testPicker
//
//Created by dxx on 2016/10/8.
//Copyright ? 2016年tyh. All rights reserved.
//
#import"ViewController.h"
@interfaceViewController()
//解析plist文件并將結(jié)果存儲到字典中忧换?為什么用字典
@property(nonatomic,strong)NSDictionary* cityNames;
//省
@property(nonatomic,strong)NSArray* provinces;
//市
@property(nonatomic,strong)NSArray* cities;
@end
@implementationViewController
//獲取數(shù)據(jù),解析plist文件
-(NSDictionary*)cityNames{
if(_cityNames==nil) {
NSString* path=[[NSBundlemainBundle]pathForResource:@"cityData"ofType:@"plist"];
_cityNames=[NSDictionarydictionaryWithContentsOfFile:path];
}
return_cityNames;
}
-(NSArray*)provinces{
if(_provinces==nil) {
_provinces=[self.cityNamesallKeys];
}
return_provinces;
}
//加載數(shù)據(jù)到組件
//1.設(shè)置組件的個數(shù)
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView{
return2;
}
//2.返回某列數(shù)據(jù)的行數(shù)
-(NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component{
if(component==0) {
return self.provinces.count;
}else{
[selfloadData:pickerView];
return self.cities.count;
}
}
//3.設(shè)置每行的文本顯示
-(NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if(component==0) {
return self.provinces[row];
}
else{
[self ?loadData:pickerView];
return ?self.cities[row];
}
}
//4.以上問題的解決都涉及到加載數(shù)據(jù)問題,寫loadData方法
-(void)loadData:(UIPickerView*)pickerView{
NSIntegerselRow=[pickerViewselectedRowInComponent:0];
NSString*key=self.provinces[selRow];
self.cities=[self.cityNamesvalueForKey:key];
}
//5.數(shù)據(jù)聯(lián)動
-(void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if(component==0) {
[pickerViewreloadComponent:1];
[pickerViewselectRow:0inComponent:1animated:YES];
}
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
plist文件結(jié)構(gòu)如下: