我尝试在用户点击UITextField时显示UIPickerView,我应该看到DataSource和Delegate Outlets将它们与选择器链接,但是,当我打开nib文件时它不会退出 - >点击文件所有者 - >检查员
第二个问题是,当我点击UItextField时,键盘没有隐藏,虽然我做了一个假设隐藏键盘的textFieldShouldReturn
方法。
我在这里缺少什么?
.h文件:
@interface RechercherViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate> {
IBOutlet UIPickerView *pickerTypesCarburants;
IBOutlet UIView *pickerViewTypesCarburants;
NSMutableArray *typesCarburantsArray;
IBOutlet UITextField *typeCarburantTextField;
}
-(IBAction)pickerTypeCarburantsShow;
-(IBAction)pickerTypeCarburantsDone;
@end
.m文件:
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [typesCarburantsArray count];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger) component{
return [typesCarburantsArray objectAtIndex:row];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch;
touch=[touches anyObject];
CGPoint point=[touch locationInView:self.view];
if(CGRectContainsPoint([typeCarburantTextField frame],point))
{
[self pickerTypeCarburantsShow];
}
}
-(IBAction)pickerTypeCarburantsDone{
NSInteger selectedRow=[pickerTypesCarburants selectedRowInComponent:0];
NSString *item=[typesCarburantsArray objectAtIndex:selectedRow];
typeCarburantTextField.text=[NSString stringWithFormat:@"%@",item];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform=CGAffineTransformMakeTranslation(0, 480);
pickerViewTypesCarburants.transform=transform;
[UIView commitAnimations];
}
-(IBAction)pickerTypeCarburantsShow{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform=CGAffineTransformMakeTranslation(0, 240);
pickerViewTypesCarburants.transform=transform;
[self.view addSubview:pickerViewTypesCarburants];
[UIView commitAnimations];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
答案 0 :(得分:2)
首先,当您点击UITextField时,您可能不应该尝试使用UIPickerView,因为它不是标准行为(特别是如果您正在压制键盘)。听起来你需要一个标准的UIButton,当按下时会显示UIPickerView,因为这会更有意义。
无论如何,如果您没有在IB中看到数据源和代理商店,请尝试在代码中手动应用它们。
pickerTypesCarburants.delegate = self;
pickerTypesCarburants.dataSource = self;
要回答第二个问题,键盘只会在您使用已实施的textFieldShouldReturn方法按回车键时隐藏。 UITextField也必须设置其委托(我假设你在IB中这样做,因为你的.m文件中没有列出)。要在按下UITextField后立即隐藏键盘,您可以更改pickerTypeCarburantsShow方法:
-(IBAction)pickerTypeCarburantsShow{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform=CGAffineTransformMakeTranslation(0, 240);
pickerViewTypesCarburants.transform=transform;
[self.view addSubview:pickerViewTypesCarburants];
[UIView commitAnimations];
[typeCarburantTextField resignFirstResponder];
}
这将确保键盘立即隐藏(而不是按下返回按钮)。再次,我会问你为什么要在点击UITextField时出现UIPickerView,因为它可能违反了人机界面指南。