2012-03-04 60 views
2

我试图用一个不同的NSArray数据更新一个UIPickerView,这个数据基于哪个索引从UISegmentedControl中选择。目前,当我更改控件时,numberOfRowsInComponent不会更新,而titleForRow只会在滚动选取器时更新。从UISegmentedControl更新UIPickerView

NSArrays在viewDidLoad中填充,我在SegmentedControl的IBAction上使用reloadAllComponents方法。

@synthesize subnetView, classControl; 

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { 

    //One column 

    return 1; 
} 

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 

    //set number of rows 

    if (classControl.selectedSegmentIndex == 0){ 
     NSLog(@"Class A Rows %d", [classAArray count]); 
     return classAArray.count; 
    } 
    else if (classControl.selectedSegmentIndex == 1){ 
     return classBArray.count; 
    } 
    else if (classControl.selectedSegmentIndex == 2){ 
     return classCArray.count; 
    } 
    return 0; 
} 
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 

    //set item per row 

    if (classControl.selectedSegmentIndex == 0){ 
     NSLog(@"Class A Rows %d", [classAArray count]); 
     return [classAArray objectAtIndex:row]; 
    } 
    else if (classControl.selectedSegmentIndex == 1){ 
     return [classBArray objectAtIndex:row]; 
    } 
    else if (classControl.selectedSegmentIndex == 2){ 
     return [classCArray objectAtIndex:row]; 
    } 
    return 0; 
} 

-(IBAction)classChange{ 

    [subnetView reloadAllComponents]; 
} 

根据哪个选择器被选择为在界面构建器中“选定”,选取器将被加载正确的数组和行数。在选择包含较少元素的数组时,根据此代码,numberOfRowsInComponents不会更新,并且应用程序将在到达较小数组末尾时崩溃。

所以我的两个问题:元素

  1. 只更新滚动时发生。
  2. 执行reloadAllComponents方法时,行数不会更新。

感谢收听!

回答

1

我以前见过这个。通常这是由于pickerview出口未连接造成的,因此无效地调用reloadAllComponents。但是,当你滚动连接的数据源和委托方法仍然工作。

这可以通过登录使用很容易地检查出口值:

NSLog(@"%@",subnetView); 

如果它记录(NULL)因为我希望它会简单地连接您的IB出口,你就大功告成了。

+0

感谢您的回复。从进行应用程序,我发现classChange没有正确执行。我在界面生成器中将TouchUpInside的出口更改为ValueChanges。一旦这个变化让所有事情都按预期开始工作。很高兴这很简单! – jcouser 2012-03-04 05:54:32