iphone - 在键盘顶部显示 TextField

标签 iphone objective-c ios

这是我的 ViewController 在 Storyboard 中的样子:

enter image description here

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

我在这个 link 中找到了 Shiun 的答案.但这并不是我想要的。

有时这个文本字段会消失在键盘后面。

当我点击 textField 并弹出键盘时:

我希望 TextField 在键盘顶部可见。

直到现在我找不到任何合适的解决方案。你能帮帮我吗?

最佳答案

没有直接的方法可以做到这一点。您将不得不收听键盘通知,然后通过找到键盘的高度将文本字段移动到键盘上方。

// 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;
}

关于iphone - 在键盘顶部显示 TextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352805/

相关文章:

ios - 传递从自定义 tableView Cell 定义的对象

ios - 只检索存储在UserDefaults中的键和值

iphone - iOS 6 View 层次结构噩梦

javascript - 在 Web 应用程序中隐藏 iPhone 状态栏?

iphone - 如何在 GLPaint 示例代码中创建自己的 recordedPath

objective-c - Cocoa 应用程序调用第 3 方 API 崩溃

ios - UITableView 的细微差别

iphone - 应用因无法启动而被拒绝? …和别的

objective-c - OSX/Cocoa 创建状态栏项目时出现问题(Apple 指南对我不起作用)

ios - 带有属性文本的 UILabel 中的 adjustsFontForContentSizeCategory