在第上一篇中,我们学习了 如何实现单组件选择器.
这一节主要是针对一些新的知识点进行说明,如果觉得我思维过快,请看上一篇.
1.double行选择器.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
return [myFirstNameArray count];
}
return [myLastNameArray count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0)
return [self.myFirstNameArray objectAtIndex:row];
return [self.myLastNameArray objectAtIndex:row];
}
由于这个是两列,所以第一列index = 0,第二列是 1. 对应的数据显示我就不说了.
2.数据绑定和plist 作为数据源.
#define KStateComponent 0
#define KzipComponet 1
@interface BIDDependentComponentPickerViewController : UIViewController<UIPickerViewDelegate,UIPickerViewDataSource>
@property (strong, nonatomic) IBOutlet UIPickerView *picker;
@property (strong,nonatomic)NSDictionary *stateZips;
@property (strong,nonatomic)NSArray *states;
@property (strong,nonatomic)NSArray *zips;
- (IBAction)ButtonPressed:(id)sender;
因为 plist 文件存放的时 state - zips 是 value-key 对,所以我们需要使用dictionary来接收.
下面的代码就是 dictionary的加载.
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *bundle =[NSBundle mainBundle];
NSURL *plistURL = [bundle URLForResource:@"statedictionary" withExtension:@"plist" ];
//得到一个路径.
NSDictionary *dictionary = [[NSDictionary alloc]initWithContentsOfURL:plistURL];
//加载
self.stateZips = dictionary;
NSArray *compoments = [self.stateZips allKeys];//得到所有的key(state).
NSArray *sorted = [compoments sortedArrayUsingSelector:@selector(compare:)];
self.states = sorted;
NSString *selectedState = [self.states objectAtIndex:0];
NSArray *array = [stateZips objectForKey:selectedState];
self.zips = array;
// Do any additional setup after loading the view from its nib.
}
3.新增的协议函数.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == KStateComponent) {
NSString *selectedState = [self.states objectAtIndex:row];
NSArray *array = [stateZips objectForKey:selectedState];
self.zips = array;
//当我重新加载了zips之后,我们也需要相应的 加载 kzipcomponent.
[picker selectRow:0 inComponent:KzipComponet animated:YES];
[picker reloadComponent:KzipComponet];
}
}
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
if (component == KStateComponent)
return 200;
return 90;
}
这段代码的意思是:如果我们发现 行列的宽和高搭配的不是很合理,我们就需要主动的设定.
还有一个设置高的协议函数.
- pickerView:rowHeightForComponent 我就不多说了.晚安,亲们~