问题
I have created UIPickerView as following . Now i want to make it resignFirstResponder if user clicks in other place then UIPickerView How could i achieve that. I have created the UIPickerView as following way.Where else could I handle
[pickerView removeFromSuperview];
-(void)pickerview:(id)sender
{
_items =[[NSArray alloc]initWithObjects:@"Hindi",@"English",@"In what city were you born?",
@"What was your childhood nickname?",
@"Type your own question.",nil];
pickerView=[[UIPickerView alloc] initWithFrame:CGRectMake(10,350,300,300)];
pickerView.transform = CGAffineTransformMakeScale(0.75f, 0.75f);
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.showsSelectionIndicator = YES;
pickerView.backgroundColor = [UIColor lightGrayColor];
[pickerView selectRow:1 inComponent:0 animated:YES];
// [self.view addSubview:pickerView];
[contentView addSubview:pickerView];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
return [_items count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return[_items objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
[Txt_SecurityQue setText:[_items objectAtIndex:row]];
NSLog(@"Did select");
}
回答1:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
UITapGestureRecognizer *tap=[[UITapGestureRecognizer
alloc]initWithTarget:self action:@selector(Tap)];
[contentView addGestureRecognizer:tap];
}
-(void)Tap {
//write the UIPickerView resignFirstResponder code......
}
回答2:
Or you can simply add :
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[pickerView removeFromSuperview];
// write resignFirstResponder code......
}
回答3:
Swift 4
Override the touchesBegan method, that is called when the user taps the view outside the pickerView. Then you can just simply call hide the pickerview.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
pickerView.isHidden = true
}
Further reading on how to use touchesBegan: https://developer.apple.com/documentation/uikit/uiresponder/1621142-touchesbegan
回答4:
- (IBAction)btnCancel_Click:(id)sender
{
[self.mypcikerview setHidden:YES];
}
- (IBAction)btnSelect_Click:(id)sender
{
NSInteger row = [myPickerView selectedRowInComponent:0];
labelQuestion.text = [NSString stringWithFormat:@"%@",[array_from objectAtIndex:row]];
[self.mypcikerview setHidden:YES];
}
where mypickerview is UIView with Pickerview , Select and cancel button
来源:https://stackoverflow.com/questions/29814658/how-to-make-uipickerview-resignfirstresponder-if-user-clicks-in-other-place-then