如何在点击返回键或点击屏幕上的任何位置时打开选择器视图?

时间:2014-08-13 10:07:16

标签: ios xcode return uipickerview numpad

我正在尝试创建一个单位转换器应用程序,并且不确定要执行哪个命令以继续进行。下面的代码会在点击数字键盘中的返回键或点击屏幕上的任何位置时返回到主屏幕。

- (IBAction)textFieldReturn:(id)sender
{
    [sender resignFirstResponder];    
    [self selectButton:nil];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch* touch= [[event allTouches]anyObject];    
    if ([_distance isFirstResponder] && [touch view] != _distance)
    {
        [_distance resignFirstResponder];
    }

    [super touchesBegan:touches withEvent:event];
}

此代码将打开一个选择器视图:

- (IBAction)selectButton:(id)sender
{
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.3];
   pickerViewContainer.frame=CGRectMake(0, 200, 320, 261);
  [UIView commitAnimations];
   pickerViewContainer.hidden=NO;
}

如何在点击返回键或点击屏幕上的任何位置时打开选择器视图?请帮助。

2 个答案:

答案 0 :(得分:4)

1-您可以使用点按手势识别器initWithTarget:self action:@selector(handleTapFrom:)];

2-使用textfield delegate -(BOOL) textFieldShouldReturn { return true; // do stuff }

答案 1 :(得分:3)

您可以在主视图上添加UITapGestureRecognizer 。并且可以利用UITextFieldDelegate来检查按下的返回按钮。

- (void) viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openPickerView)];
    [self.view addGestureRecognizer:gestureRecognizer];
    [self.textField setDelegate:self];
}

//UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self openPickerView];
    return YES;
}


- (void)openPickerView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    pickerViewContainer.frame=CGRectMake(0, 200, 320, 261);
    [UIView commitAnimations];
    pickerViewContainer.hidden=NO;
}