我正在尝试使用以下代码的基本UI选择器视图
- (void)viewDidLoad
{
[super viewDidLoad];
self.MainPicker.delegate = self;
self.MainPicker.dataSource = self;
[self.MainPicker selectRow:1 inComponent:0 animated:NO];
_countryNames = @[@"Australia (AUD)", @"China (CNY)",
@"France (EUR)", @"Great Britain (GBP)", @"Japan (JPY)"];
//NSLog(@"%@", [_countryNames objectAtIndex:0]);
_exchangeRates = @[ @0.9922f, @6.5938f, @0.7270f,
@0.6206f, @81.57f];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
float rate = [_exchangeRates[row] floatValue];
float dollars = 10.0;
float result = dollars * rate;
NSString *resultString = [[NSString alloc] initWithFormat:
@"%.2f USD = %.2f %@", dollars, result,
_countryNames[row]];
NSLog(@"%@",resultString);
[pickerView reloadAllComponents];
}
- (IBAction)Submit:(id)sender {
}
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return _countryNames.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return _countryNames[row];
}
@end
当我说明
时获得例外2013-12-09 15:46:11.174 pickerExample [20718:a0b] - [UIView numberOfComponentsInPickerView:]:发送到无法识别的选择器 实例0x9880e80 2013-12-09 15:46:11.260 pickerExample [20718:a0b] * 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [UIView numberOfComponentsInPickerView:]:发送到无法识别的选择器 实例0x9880e80'。
我已将数据源和委托链接到当前视图控制器。任何人都可以指导我出错的地方!!
答案 0 :(得分:0)
在设置[self.MainPicker selectRow:1 inComponent:0 animated:NO];
之前,您的问题是调用datasource
方法。实际上你甚至试图在setting up UIPicker
之前选择一行
所以在调用此方法之前设置_countryNames
和_exchangeRates
,如下所示......
初始化数据源
_countryNames = @[@"Australia (AUD)", @"China (CNY)",
@"France (EUR)", @"Great Britain (GBP)", @"Japan (JPY)"];
//NSLog(@"%@", [_countryNames objectAtIndex:0]);
_exchangeRates = @[ @0.9922f, @6.5938f, @0.7270f,
@0.6206f, @81.57f];
//方法调用
self.MainPicker.delegate = self;
self.MainPicker.dataSource = self;
[self.MainPicker selectRow:1 inComponent:0 animated:NO];