How to make UIPickerView resignFirstResponder if user clicks in other place then UIPickerView

时间:2015-04-23 05:43:05

标签: ios objective-c xcode uipickerview

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");
}

4 个答案:

答案 0 :(得分:2)

或者你可以简单地添加:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [pickerView removeFromSuperview]; 
        // write resignFirstResponder code......
}

答案 1 :(得分: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 :(得分:1)

Swift 4

覆盖touchesBegan方法,当用户点击pickerView外部的视图时调用该方法。然后你可以简单地调用hide pickerview。

override func touchesBegan(_ touches: Set<UITouch>, with event:   UIEvent?) {
    pickerView.isHidden = true
}

进一步阅读如何使用touchesBegan: https://developer.apple.com/documentation/uikit/uiresponder/1621142-touchesbegan

答案 3 :(得分:0)

enter image description here

- (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