[新手学ios]第三天:使用tab Bar Controller 实现多组件选择器和组关联(plist和数据绑定)

在第上一篇中,我们学习了 如何实现单组件选择器.

这一节主要是针对一些新的知识点进行说明,如果觉得我思维过快,请看上一篇.

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;
}
这段代码的意思是:如果我们发现 行列的宽和高搭配的不是很合理,我们就需要主动的设定.

还有一个设置高的协议函数.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值