您的位置:首页 > 产品设计 > UI/UE

用UIPicker做一个类似省市联动选择的例子

2013-08-16 11:20 141 查看
用UIPicker做一个类似省市联动选择的例子
ViewController.h:

#import <UIKit/UIKit.h> @interface ForthViewController :UIViewController<UIPickerViewDataSource,UIPickerViewDelegate> @property (retain,nonatomic) IBOutlet UIPickerView *picker; @property(nonatomic,retain)NSDictionary *dictionary; @property(nonatomic,retain)NSArray *states; //省 @property(nonatomic,retain)NSArray *zips;//市 @end ViewController.m:

#import"ForthViewController.h" #define STATE_COMPONENT0 #define ZIP_COMPONENT 1 @interfaceForthViewController ()
@end
@implementation ForthViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; }
- (void)viewDidLoad { [superviewDidLoad]; NSBundle *bundle = [NSBundle mainBundle];//目录,地址 NSURL * url = [bundle URLForResource:@"statedictionary"withExtension:@"plist"]; NSString *path = [bundle pathForResource:@"statedictionary"ofType:@"plist"]; NSLog(@"%@",url); NSLog(@"%@",path); NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path]; self.dictionary = dic; NSLog(@"%@",self.dictionary); NSArray *arr = [self.dictionaryallKeys]; self.states = arr; arr= [self.dictionaryobjectForKey:self.states[0]]; self.zips = arr; }
- (void)didReceiveMemoryWarning { [superdidReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //一个picker有几个compont -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return2; } //每个组件有几行数据 -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { //创建数据 if(component ==STATE_COMPONENT) { return [self.states count]; //动态获取数字 } else { return [self.zips count]; } } //每行显示的内容 -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if (component ==STATE_COMPONENT) { return [self.states objectAtIndex:row]; } else { return [self.zips objectAtIndex:row]; } } //选择一行就触发的事件 -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if (component ==STATE_COMPONENT) { NSString *str = [self.statesobjectAtIndex:row]; NSArray *arr = [self.dictionaryvalueForKey:self.states[row]]; self.zips = arr; //因为component = ZIP_COMPONENT的数据发生改变,所以要重新导入 [pickerView reloadComponent:ZIP_COMPONENT]; //防止越界,row超过现在的总行数 [pickerViewselectRow:0inComponent:ZIP_COMPONENTanimated:YES]; } }
- (void)dealloc { [_pickerrelease]; [_dictionaryrelease]; [_statesrelease]; [_zipsrelease]; [superdealloc]; } @end

项目源码:http://download.csdn.net/detail/s10141303/5958499
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: