在将文本输入文本字段时,键盘隐藏在两者之间

时间:2016-04-25 12:35:22

标签: ios objective-c keyboard uitapgesturerecognizer first-responder

我正在使用包含滚动视图的登录屏幕,在滚动视图上有两个带有登录按钮的文本字段。

scrollview用于调整iphone 5的屏幕尺寸。我正在使用"标签手势"因此,如果任何用户在文本字段中输入文本并想要隐藏键盘,则可以单击屏幕上的任意位置以隐藏键盘。用于标签手势的函数是

- (void)viewDidLoad {

NSLog(@"login view");

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[self.scrollView addGestureRecognizer:singleTap]; }

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
[self.view endEditing:YES]; }

我的问题是当用户使用键盘在文本字段中输入文本时,在输入文本键盘的过程中,键盘检测到标签手势并将键盘隐藏在中间。

我为解决这个问题做了什么: - 1.)我改变了[self.view addGestureRecognizer:singleTap];

2。)我在屏幕顶部放置了视图(0,0,360,400)并将手势应用于此视图,以便单击此视图将隐藏键盘但仍然在用户通过调用手势方法键入键盘隐藏时

3。)我还在屏幕尺寸的一半的滚动视图上使用了一个按钮,因此用户可以点击任何地方隐藏键盘,但键入窗台,即使然后键盘隐藏y调用按钮的ibaction方法

4 个答案:

答案 0 :(得分:3)

删除Tapgesture并尝试使用此代码,这将有所帮助。

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}

答案 1 :(得分:2)

使用此按钮隐藏键盘并显示键盘: -

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == username)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];

    }
    if (textField == password)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];

    }

    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == username)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];
    }

    if (textField == password)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidShowNotification object:nil];

    }
    return YES;
}


- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    float newVerticalPosition = -keyboardSize.height + 100;

    [self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
}


- (void)keyboardWillHide:(NSNotification *)notification
{
    CGFloat  kNavBarHeight =  self.navigationController.navigationBar.frame.size.height;
    [self moveFrameToVerticalPosition:kNavBarHeight forDuration:0.3f];
}

- (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration
{
    CGRect frame = self.view.frame;
    frame.origin.y = position;

    [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
    }];
}

答案 2 :(得分:2)

我找到了最好的解决方案。首先,您要整合pod'TPKeyboardAvoiding','〜&gt; 1.2.3',然后添加TPKeyboardAvoidingScrollView类。它将处理所有。不必编写额外的代码。

答案 3 :(得分:1)

尝试这样,

/usr/local/engine

希望这会有所帮助:)