键盘出现时滚动视图:库还是DIY?

时间:2013-02-20 03:23:01

标签: iphone ios xcode

当用户点击相应的对象看起来无缝时,我试图让整个视图移动到适当的UITextField。我知道我并不是唯一一个绝对讨厌这样做的人。

尽可能以最少的工作量使这项工作尽可能精美,最好的方法是什么?

我已经尝试了TPKeyboardAvoiding,但它完全被吸了。

现在,我已经开始使用此代码,但它的特殊方式也很糟糕:

- (void)viewDidLoad
{
    self.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin);
    self.scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin);

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

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


- (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.scrollView.contentInset = contentInsets;
    self.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, self.activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-kbSize.height);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification *)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
}

2 个答案:

答案 0 :(得分:1)

对我而言,它有效TPKeyboardAvoiding,我在所有项目中都使用它。你试过:

  1. 将UIScrollView添加到视图控制器的xib
  2. 将滚动视图的类设置为TPKeyboardAvoidingScrollView(仍然是 在xib,通过身份检查员)
  3. 将所有控件放在该滚动视图中?
  4. 我也找到了这个解决方案:Keyboard Manager

    1. 下载演示项目
    2. 只需将KeyboardManager和SegmenedNextPrevious类拖放到项目中
    3. 即可
    4. 在你的appDelegate中只写一行代码:

      [KeyBoardManager installKeyboardManager];

    5. 祝你好运!

答案 1 :(得分:0)

您是否知道如果您的视图控制器派生自UITableViewController,当文本字段或文本视图获得焦点时键盘显示时,滚动表视图是否自动?你不需要做任何事情。话虽如此,它可能无法很好地为您的应用重构UI,以便它使用静态单元格的表格视图,而不是现在正在做的任何事情。

如果这对您不起作用,您可以在显示键盘时将滚动视图的contenSize更改为可见区域的大小,然后在滚动视图上调用scrollRectToVisible:animated:并将其传递给rect您的keyboardWasShown:selector中的文本字段。