简体   繁体   English

在键盘顶部显示 TextField

[英]Display TextField at the top of Keyboard

This is how my ViewController looks like in Storyboard:这是我的 ViewController 在 Storyboard 中的样子:

在此处输入图片说明

@interface SettingViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, NSURLConnectionDelegate> { }

I found an answer by Shiun in this link .我在此链接中找到了 Shiun 的答案。 but that is not exactly what I am looking for.但这并不是我正在寻找的。

Sometimes this Text Field become disappear behind the keyboard.有时这个文本字段会消失在键盘后面。

When I click on the textField and keyboard pops up :当我点击 textField 并弹出键盘时:

I want the TextField to be visible at the top of keyboard.我希望 TextField 在键盘顶部可见。

I could not find any proper solution until now.直到现在我找不到任何合适的解决方案。 Could you help me?你可以帮帮我吗?

There is no direct way of doing this.没有直接的方法可以做到这一点。 You will have to listen to keyboard notifications and then move the text field above the keyboard by finding the height of the keyboard.您必须听取键盘通知,然后通过查找键盘的高度将文本字段移动到键盘上方。

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];

   [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(keyboardWillBeHidden:)
             name:UIKeyboardWillHideNotification object:nil];

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM