用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
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
{
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
NSLog(@"%@",self.dictionary);
NSArray *arr = [self.dictionaryallKeys];
self.states
self.dictionaryobjectForKey:self.states[0]];
self.zips
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
}
//一个picker有几个compont
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView
{
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
//因为component = ZIP_COMPONENT的数据发生改变,所以要重新导入
reloadComponent:ZIP_COMPONENT];
//防止越界,row超过现在的总行数
[pickerViewselectRow:0inComponent:ZIP_COMPONENTanimated:YES];
}
}
- (void)dealloc {
_pickerrelease];
[_dictionaryrelease];
_statesrelease];
_zipsrelease];
superdealloc];
}
@end