我试图在同一 View 中有2 pickerviews。它起作用,除了两件事。如果一个pickerview的行多于另一个,则当从pickerview中选择包含更多项目的项目时,应用程序将崩溃。我还为pickerviews创建了一个NSLog,控制台显示我一次选择了两个项目,而实际上我只在处理一个pickerview。我知道这听起来有些混乱,但是我包含了所有代码。先感谢您。
list和list2是NSMutableArrays
清单有4个项目
list2有5个项目
出现错误:
*由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[NSCFArray objectAtIndex:]:索引(4)超出范围(4)”
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView{
if([thePickerView isEqual:pickerView1 ]){
return 1;
}
else if([thePickerView isEqual:pickerView2]){
return 1;
}
else{
return 0;
}
}
-(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component{
if([thePickerView isEqual:pickerView1 ]){
return [list count];
}
else if([thePickerView isEqual:pickerView2]){
return [list2 count];
}
else{
return 0;
}
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if([thePickerView isEqual:pickerView1 ]){
return [list objectAtIndex:row];
}
else if([thePickerView isEqual:pickerView2]){
return [list2 objectAtIndex:row];
}
else{
return 0;
}
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSLog(@"Selected item %@. Index of selected item:%i", [list objectAtIndex:row], row);
NSLog(@"Selected item %@. Index of selected item:%i", [list2 objectAtIndex:row], row);
NSLog(@"Selected item %@. Index of selected item:%i", [list3 objectAtIndex:row], row);
if([thePickerView isEqual:pickerView1 ]){
//Do Something
}
else if([thePickerView isEqual:pickerView2 ]){
//Do Something
}
else if([thePickerView isEqual:pickerView3 ]){
//Do Something
}
}
最佳答案
您的问题在这里:
NSLog(@"Selected item %@. Index of selected item:%i", [list objectAtIndex:row], row);
NSLog(@"Selected item %@. Index of selected item:%i", [list2 objectAtIndex:row], row);
NSLog(@"Selected item %@. Index of selected item:%i", [list3 objectAtIndex:row], row);
发生的情况是,向上述列表之一发送了一条消息,以返回超出其范围的对象。在将消息发送到日志之前,您应该检查 call 来自哪个选择器:
if([thePickerView isEqual:pickerView1 ]){
NSLog(@"Selected item %@. Index of selected item:%i", [list objectAtIndex:row], row);
//Do Something
}
else if([thePickerView isEqual:pickerView2 ]){
NSLog(@"Selected item %@. Index of selected item:%i", [list2 objectAtIndex:row], row);
//Do Something
}
else if([thePickerView isEqual:pickerView3 ]){
NSLog(@"Selected item %@. Index of selected item:%i", [list3 objectAtIndex:row], row);
//Do Something
}
关于iphone - 保存 View 时出现两个PickerViews问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2484858/