ios 选择文本字段时使 UITableView 滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/594181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:41:43  来源:igfitidea点击:

Making a UITableView scroll when text field is selected

iosiphoneuitableviewkeyboardscroll

提问by

After a lot of trial and error, I'm giving up and asking the question. I've seen a lot of people with similar problems but can't get all the answers to work right.

经过大量的反复试验,我放弃并提出问题。我见过很多人有类似的问题,但无法得到所有正确的答案。

I have a UITableViewwhich is composed of custom cells. The cells are made of 5 text fields next to each other (sort of like a grid).

我有一个UITableView由自定义单元格组成的。这些单元格由 5 个彼此相邻的文本字段组成(有点像网格)。

When I try to scroll and edit the cells at the bottom of the UITableView, I can't manage to get my cells properly positioned above the keyboard.

当我尝试滚动和编辑 底部的单元格时UITableView,我无法将单元格正确放置在键盘上方。

I have seen many answers talking about changing view sizes,etc... but none of them has worked nicely so far.

我已经看到很多关于改变视图大小等的答案......但到目前为止,它们都没有很好地工作。

Could anybody clarify the "right" way to do this with a concrete code example?

任何人都可以通过具体的代码示例来阐明“正确”的方法吗?

回答by Sam Ho

If you use UITableViewController instead of UIViewController, it will automatically do so.

如果你使用 UITableViewController 而不是 UIViewController,它会自动这样做。

回答by user91083

The function that does the scrolling could be much simpler:

执行滚动的函数可能要简单得多:

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    UITableViewCell *cell;

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
    // Load resources for iOS 6.1 or earlier
        cell = (UITableViewCell *) textField.superview.superview;

    } else {
        // Load resources for iOS 7 or later
        cell = (UITableViewCell *) textField.superview.superview.superview; 
       // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
    }
    [tView scrollToRowAtIndexPath:[tView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

That's it. No calculations at all.

就是这样。根本没有计算。

回答by ZeLegolas

I'm doing something very similar it's generic, no need to compute something specific for your code. Just check the remarks on the code:

我正在做一些非常相似的事情,它是通用的,不需要为您的代码计算特定的东西。只需检查代码上的注释:

In MyUIViewController.h

在 MyUIViewController.h

@interface MyUIViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
{
     UITableView *myTableView;
     UITextField *actifText;
}

@property (nonatomic, retain) IBOutlet UITableView *myTableView;
@property (nonatomic, retain) IBOutlet UITextField *actifText;

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;
- (IBAction)textFieldDidEndEditing:(UITextField *)textField;

-(void) keyboardWillHide:(NSNotification *)note;
-(void) keyboardWillShow:(NSNotification *)note;

@end

In MyUIViewController.m

在 MyUIViewController.m 中

@implementation MyUIViewController

@synthesize myTableView;
@synthesize actifText;

- (void)viewDidLoad 
{
    // Register notification when the keyboard will be show
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillShow:)
                                          name:UIKeyboardWillShowNotification
                                          object:nil];

    // Register notification when the keyboard will be hide
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillHide:)
                                          name:UIKeyboardWillHideNotification
                                          object:nil];
}

// To be link with your TextField event "Editing Did Begin"
//  memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.actifText = textField;
}

// To be link with your TextField event "Editing Did End"
//  release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.actifText = nil;
}

-(void) keyboardWillShow:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    // Start animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height -= keyboardBounds.size.height;
    else 
        frame.size.height -= keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    // Scroll the table view to see the TextField just above the keyboard
    if (self.actifText)
      {
        CGRect textFieldRect = [self.myTableView convertRect:self.actifText.bounds fromView:self.actifText];
        [self.myTableView scrollRectToVisible:textFieldRect animated:NO];
      }

    [UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Increase size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height += keyboardBounds.size.height;
    else 
        frame.size.height += keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    [UIView commitAnimations];
}

@end


Swift 1.2+ version:

斯威夫特 1.2+ 版本:

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var activeText: UITextField!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillShow:"),
            name: UIKeyboardWillShowNotification,
            object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillHide:"),
            name: UIKeyboardWillHideNotification,
            object: nil)
    }

    func textFieldDidBeginEditing(textField: UITextField) {
        activeText = textField
    }

    func textFieldDidEndEditing(textField: UITextField) {
        activeText = nil
    }

    func keyboardWillShow(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height -= keyboardSize.height
            tableView.frame = frame
            if activeText != nil {
                let rect = tableView.convertRect(activeText.bounds, fromView: activeText)
                tableView.scrollRectToVisible(rect, animated: false)
            }
            UIView.commitAnimations()
        }
    }

    func keyboardWillHide(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height += keyboardSize.height
            tableView.frame = frame
            UIView.commitAnimations()
        }
    }
}

回答by squall2022

The simplest solution for Swift 3, based on Bart?omiej Semańczyk solution:

Swift 3最简单的解决方案,基于Bart?omiej Semańczyk 解决方案

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(CreateEditRitualViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(CreateEditRitualViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

// MARK: Keyboard Notifications

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardHeight = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {
        tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2, animations: {
        // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
    })
}

回答by phse

I had the same problem but noticed that it appears only in one view. So I began to look for the differences in the controllers.

我有同样的问题,但注意到它只出现在一个视图中。所以我开始寻找控制器的差异。

I found out that the scrolling behavior is set in - (void)viewWillAppear:(BOOL)animatedof the super instance.

我发现滚动行为是在- (void)viewWillAppear:(BOOL)animated超级实例中设置的。

So be sure to implement like this:

所以一定要这样实现:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // your code
}

And it doesn't matter if you use UIViewControlleror UITableViewController; checked it by putting a UITableViewas a subview of self.view in the UIViewController. It was the same behavior. The view didn't allow to scroll if the call [super viewWillAppear:animated];was missing.

如果您使用UIViewControllerUITableViewController,则无关紧要;通过将 aUITableView作为 self.view 的子视图放入UIViewController. 这是同样的行为。如果呼叫[super viewWillAppear:animated];丢失,视图不允许滚动。

回答by mickm

i may have missed this, as i didn't read the whole post here, but what i came up with seems deceptively simple. i haven't put this through the wringer, testing in all situations, but it seems like it should work just fine.

我可能错过了这个,因为我没有在这里阅读整篇文章,但我想出的东西似乎很简单。我还没有把它通过绞拧器,在所有情况下进行测试,但看起来它应该可以正常工作。

simply adjust the contentInset of the tableview by the height of the keyboard, and then scroll the cell to the bottom:

只需通过键盘的高度调整 tableview 的 contentInset,然后将单元格滚动到底部:

- (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);
    self.myTableView.contentInset = contentInsets;
    self.myTableView.scrollIndicatorInsets = contentInsets;

    [self.myTableView scrollToRowAtIndexPath:self.currentField.indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

and of course

而且当然

- (void)keyboardWasHidden:(NSNotification *)aNotification
{
    [UIView animateWithDuration:.3 animations:^(void) 
    {
        self.myTableView.contentInset = UIEdgeInsetsZero;
        self.myTableView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }];
}

is this too simple? am i missing something? so far it is working for me fine, but as i said, i haven't put it through the wringer...

这太简单了?我错过了什么吗?到目前为止它对我来说很好,但正如我所说,我还没有通过绞拧器......

回答by Ortwin Gentz

If you can use UITableViewController, you get the functionality for free. Sometimes, however, this is not an option, specifically if you need multiple views not just the UITableView.

如果您可以使用UITableViewController,您将免费获得该功能。但是,有时这不是一种选择,特别是如果您需要多个视图而不仅仅是UITableView.

Some of the solutions presented here don't work on iOS ≥4, some don't work on iPad or in landscape mode, some don't work for Bluetooth keyboards (where we don't want any scrolling), some don't work when switching between multiple text fields. So if you choose any solution, make sure to test these cases. This is the solution we useusedin InAppSettingsKit:

这里介绍的一些解决方案不适用于 iOS ≥4,有些不适用于 iPad 或横向模式,有些不适用于蓝牙键盘(我们不需要任何滚动),有些则不起作用在多个文本字段之间切换时工作。因此,如果您选择任何解决方案,请务必测试这些案例。这是我们的解决方案使用用于InAppSettingsKit

- (void)_keyboardWillShow:(NSNotification*)notification {
    if (self.navigationController.topViewController == self) {
        NSDictionary* userInfo = [notification userInfo];

        // we don't use SDK constants here to be universally compatible with all SDKs ≥ 3.0
        NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
        if (!keyboardFrameValue) {
            keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
        }

        // Reduce the tableView height by the part of the keyboard that actually covers the tableView
        CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
        if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
            windowRect = IASKCGRectSwap(windowRect);
        }
        CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
        if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
            viewRectAbsolute = IASKCGRectSwap(viewRectAbsolute);
        }
        CGRect frame = _tableView.frame;
        frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
        [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        _tableView.frame = frame;
        [UIView commitAnimations];

        UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
        NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];

        // iOS 3 sends hide and show notifications right after each other
        // when switching between textFields, so cancel -scrollToOldPosition requests
        [NSObject cancelPreviousPerformRequestsWithTarget:self];

        [_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
}

- (void) scrollToOldPosition {
  [_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)_keyboardWillHide:(NSNotification*)notification {
    if (self.navigationController.topViewController == self) {
        NSDictionary* userInfo = [notification userInfo];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
        [UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
        _tableView.frame = self.view.bounds;
        [UIView commitAnimations];

        [self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
    }
}   

Here's the full code of the classin InAppSettingsKit. To test it, use the "Complete List" child pane where you can test the scenarios mentioned above.

这是InAppSettingsKit 中完整代码。要测试它,请使用“完整列表”子窗格,您可以在其中测试上述场景。

回答by Michael Baltaks

I think I've come up with the solution to match the behaviour of Apple's apps.

我想我已经提出了与 Apple 应用程序行为相匹配的解决方案。

First, in your viewWillAppear: subscribe to the keyboard notifications, so you know when the keyboard will show and hide, and the system will tell you the size of the keyboard, but dont' forget to unregister in your viewWillDisappear:.

首先,在您的 viewWillAppear: 订阅键盘通知,这样您就知道键盘何时显示和隐藏,系统会告诉您键盘的大小,但不要忘记在您的 viewWillDisappear: 中取消注册。

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

Implement the methods similar to the below so that you adjust the size of your tableView to match the visible area once the keyboard shows. Here I'm tracking the state of the keyboard separately so I can choose when to set the tableView back to full height myself, since you get these notifications on every field change. Don't forget to implement keyboardWillHide: and choose somewhere appropriate to fix your tableView size.

实现类似于下面的方法,以便在键盘显示后调整 tableView 的大小以匹配可见区域。在这里,我单独跟踪键盘的状态,因此我可以选择何时将 tableView 设置回全高,因为您会在每个字段更改时收到这些通知。不要忘记实现 keyboardWillHide: 并选择合适的地方来修复您的 tableView 大小。

-(void) keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    if (keyboardIsShowing == NO)
    {
        keyboardIsShowing = YES;
        CGRect frame = self.view.frame;
        frame.size.height -= keyboardHeight;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

Now here's the scrolling bit, we work out a few sizes first, then we see where we are in the visible area, and set the rect we want to scroll to to be either the half view above or below the middle of the text field based on where it is in the view. In this case, we have an array of UITextFields and an enum that keeps track of them, so multiplying the rowHeight by the row number gives us the actual offset of the frame within this outer view.

现在这里是滚动位,我们首先计算出一些尺寸,然后我们看到我们在可见区域中的位置,并将我们想要滚动的矩形设置为基于文本字段中间上方或下方的半视图它在视图中的位置。在这种情况下,我们有一个 UITextField 数组和一个跟踪它们的枚举,因此将 rowHeight 乘以行号为我们提供了此外部视图中框架的实际偏移量。

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    CGFloat rowHeight = self.tableView.rowHeight;
    if (textField == textFields[CELL_FIELD_ONE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_ONE;
    }
    else if (textField == textFields[CELL_FIELD_TWO])
    {
        frame.origin.y += rowHeight * CELL_FIELD_TWO;
    }
    else if (textField == textFields[CELL_FIELD_THREE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_THREE;
    }
    else if (textField == textFields[CELL_FIELD_FOUR])
    {
        frame.origin.y += rowHeight * CELL_FIELD_FOUR;
    }
    CGFloat viewHeight = self.tableView.frame.size.height;
    CGFloat halfHeight = viewHeight / 2;
    CGFloat midpoint = frame.origin.y + (textField.frame.size.height / 2);
    if (midpoint < halfHeight)
    {
        frame.origin.y = 0;
        frame.size.height = midpoint;
    }
    else
    {
        frame.origin.y = midpoint;
        frame.size.height = midpoint;
    }
    [self.tableView scrollRectToVisible:frame animated:YES];
}

This seems to work quite nicely.

这似乎工作得很好。

回答by Bart?omiej Semańczyk

The simplest solution for Swift:

Swift最简单的解决方案:

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar?.becomeFirstResponder()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillShow(_:)), name: UIKeyboardDidShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillHide(_:)), name: UIKeyboardDidHideNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.size.height {
            tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    UIView.animateWithDuration(0.2, animations: { self.table_create_issue.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) })
    // For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
    }

回答by Hussain KMR Behestee

I hope you guys already got a solution reading all those. But I found my solution as follows. I am expecting that you already have a cell with UITextField. So on preparing just keep the row index into the text field's tag.

我希望你们已经有一个解决方案阅读所有这些。但我发现我的解决方案如下。我期待你已经有一个带有UITextField. 因此,在准备时只需将行索引保留在文本字段的标签中。

cell.textField.tag = IndexPath.row;

Create an activeTextField, instance of UITextFieldwith global scope as below:

创建一个具有全局作用域的activeTextField, 实例,UITextField如下所示:

@interface EditViewController (){

    UITextField *activeTextField;

}

So, now you just copy paste my code at the end. And also don't forget to add UITextFieldDelegate

所以,现在你只需在最后复制粘贴我的代码。并且不要忘记添加UITextFieldDelegate

#pragma mark - TextField Delegation

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    activeTextField = textField;

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    activeTextField = nil;

}

Registers keyboard notifications

寄存器键盘 notifications

#pragma mark - Keyboard Activity

- (void)registerForKeyboardNotifications

{

    [[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(keyboardWasShown:)

                                             name:UIKeyboardDidShowNotification object:nil];



    [[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(keyboardWillBeHidden:)

                                             name:UIKeyboardWillHideNotification object:nil];



}

Handles Keyboard Notifications:

手柄键盘Notifications

Called when the UIKeyboardDidShowNotificationis sent.

UIKeyboardDidShowNotification发送时调用。

- (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);

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

    NSIndexPath *currentRowIndex = [NSIndexPath indexPathForRow:activeTextField.tag inSection:0];

    [self.tableView scrollToRowAtIndexPath:currentRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

Called when the UIKeyboardWillHideNotificationis sent

UIKeyboardWillHideNotification发送时调用

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    [self.tableView setContentInset:contentInsets];

    [self.tableView setScrollIndicatorInsets:contentInsets];

}

Now one thing is left, Call the registerForKeyboardNotificationsmethod in to ViewDidLoadmethod as follows:

现在还剩下一件事,将registerForKeyboardNotifications方法调用到ViewDidLoad方法中,如下所示:

- (void)viewDidLoad {

    [super viewDidLoad];

    // Registering keyboard notification

    [self registerForKeyboardNotifications];

    // Your codes here...

}

You are done, hope your textFieldswill no longer hidden by the keyboard.

大功告成,希望你textFields不再被键盘隐藏。