单击文本字段以从键盘输入文本时,将文本字段设置为顶部

时间:2016-03-16 11:08:16

标签: ios uitextfield animated

我是iOS新手,刚开始设计登录表单。当用户单击文本字段时,会出现隐藏文本字段的键盘,因此无法看到文本字段。  因此,如何在键盘出现时将文本字段设置为顶部。

1 个答案:

答案 0 :(得分:0)

你可以尝试这个 - >

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

    }return YES;
}

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


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

    float newVerticalPosition = -keyboardSize.height + 10;

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


- (void)keyboardWillHide:(NSNotification *)notification
{
    CGFloat  kNavBarHeight =  self.navigationController.navigationBar.frame.size.height;
    float newVerticalPosition = kNavBarHeight  -45;

    [self moveFrameToVerticalPosition:newVerticalPosition 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;
    }];
}