显示键盘时将UITextField滚动到视图中 [英] Scrolling UITextField into view when keyboard is shown

查看:82
本文介绍了显示键盘时将UITextField滚动到视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写针对iOS 6.1的应用程序.我正在尝试遵循此

I'm writing an app targeting iOS 6.1. I'm trying to follow this Apple doc on how to scroll a UITextField into view if it is obscured by the keyboard. The problem is that Apple's documented algorithm for calculating the scroll point doesn't work so well. My algorithm for calculating the scroll point works only slightly better, but is off by 70 pixels. What is the correct way to calculate the scroll point?

在下面,您可以从左到右查看显示键盘之前的视图,使用Apple算法计算滚动点后的视图以及使用算法计算滚动点后的视图. (该网格中的每个正方形都是25像素乘25像素.)

Below you can see, from left to right, my view before the keyboard is shown, my view after scrolling using Apple's algorithm to calculate the scroll point, and my view after scrolling using my algorithm to calculate the scroll point. (Each square in that grid is 25 pixels by 25 pixels.)

这是我正在使用的代码.请注意#if APPLE_WAY块.

And here is the code I am using. Note the #if APPLE_WAY block.

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

#if APPLE_WAY
        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-kbSize.height);
#else
        CGFloat offset = self.activeField.frame.origin.y;

        //TODO: Why is this off by 70?
        offset = offset - 70;

        CGPoint scrollPoint = CGPointMake(0.0, offset);
#endif
        [self.view setContentOffset:scrollPoint animated:YES];
    }
}

推荐答案

您只需要将偏移量设置为键盘的高度:

You simply need to set the offset to the height of the keyboard:

CGFloat offset = kbSize.height;
CGPoint scrollPoint = CGPointMake(0.0, offset);
[self.view setContentOffset:scrollPoint animated:YES];

希望这会有所帮助

这篇关于显示键盘时将UITextField滚动到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆