【问题标题】:Trying to move the view up when the keyboard is showing显示键盘时尝试向上移动视图
【发布时间】:2013-01-18 12:53:28
【问题描述】:

我试图在键盘显示时将视图向上推(它覆盖了我希望用户在输入时看到的数据。我正在使用此代码:

KBKeyboardHandler.h

@protocol KBKeyboardHandlerDelegate;

@interface KBKeyboardHandler : NSObject

- (id)init;

// Put 'weak' instead of 'assign' if you use ARC
@property(nonatomic, assign) id<KBKeyboardHandlerDelegate> delegate; 
@property(nonatomic) CGRect frame;

@end

KBKeyboardHandler.m

#import "KBKeyboardHandler.h"
#import "KBKeyboardHandlerDelegate.h"

@implementation KBKeyboardHandler

- (id)init
{
    self = [super init];
    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];

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

    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

@synthesize delegate;
@synthesize frame;

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGRect oldFrame = self.frame;    
    [self retrieveFrameFromNotification:notification];

    if (oldFrame.size.height != self.frame.size.height)
    {
        CGSize delta = CGSizeMake(self.frame.size.width - oldFrame.size.width,
                                  self.frame.size.height - oldFrame.size.height);
        if (self.delegate)
            [self notifySizeChanged:delta notification:notification];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    if (self.frame.size.height > 0.0)
    {
        [self retrieveFrameFromNotification:notification];
        CGSize delta = CGSizeMake(-self.frame.size.width, -self.frame.size.height);

        if (self.delegate)
            [self notifySizeChanged:delta notification:notification];
    }

    self.frame = CGRectZero;
}

- (void)retrieveFrameFromNotification:(NSNotification *)notification
{
    CGRect keyboardRect;
    [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardRect];
    self.frame = [[UIApplication sharedApplication].keyWindow.rootViewController.view convertRect:keyboardRect fromView:nil];
}

- (void)notifySizeChanged:(CGSize)delta notification:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];

    UIViewAnimationCurve curve;
    [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];

    NSTimeInterval duration;
    [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];

    void (^action)(void) = ^{
        [self.delegate keyboardSizeChanged:delta];
    };

    [UIView animateWithDuration:duration
                          delay:0.0
                        options:curve
                     animations:action
                     completion:nil];    
}

@end

KBKeyboardHandlerDelegate.h

@protocol KBKeyboardHandlerDelegate

- (void)keyboardSizeChanged:(CGSize)delta;

@end

示例 MyViewController.h

@interface MyViewController : UIViewController<KBKeyboardHandlerDelegate>
...
@end

示例 MyViewController.m

@implementation MyViewController
{
    KBKeyboardHandler *keyboard;
}

- (void)dealloc
{
    keyboard.delegate = nil;
    [keyboard release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    keyboard = [[KBKeyboardHandler alloc] init];
    keyboard.delegate = self;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    keyboard.delegate = nil;
    [keyboard release];
    keyboard = nil;
}

- (void)keyboardSizeChanged:(CGSize)delta
{
    // Resize / reposition your views here. All actions performed here 
    // will appear animated.
    // delta is the difference between the previous size of the keyboard 
    // and the new one.
    // For instance when the keyboard is shown, 
    // delta may has width=768, height=264,
    // when the keyboard is hidden: width=-768, height=-264.
    // Use keyboard.frame.size to get the real keyboard size.

    // Sample:
    CGRect frame = self.view.frame;
    frame.size.height -= delta.height;
    self.view.frame = frame;
}

我找到了here。我试图弄清楚为什么我的观点没有推高。键盘正在显示,keyboardSizeChanged 被启动,但视图没有移动。我打开了一个新项目并将 KBKeyboardHandler 和委托文件复制到它,实现了代码,并且在新项目中它工作正常,所以我知道这是我原始项目中的一些东西搞砸了。知道它是什么吗?

【问题讨论】:

    标签: ios objective-c cocoa-touch


    【解决方案1】:

    如果您不使用 UITableView,请使用 UIScrollView 作为元素的父视图并添加以下代码 按需调整,

    您将需要一个 NSArray 的 NSObjects,我调用了我的 scrollToObjects 并在 viewDidLoad 中将元素添加到需要滚动的数组中,这样当调用 keyboardWasShown 时,您可以检查当前选择的元素是否应该滚动到。

    我使用 self.activeField 来存储我当前选择的元素,该元素在元素触发事件时设置(该事件需要是第一个被调用的事件之一,并且总是被调用)

    然后我检查 scrollToObjects 是否包含 activeField 以及它是否向上滚动 UIScrollView 然后在 activeField resignsFirstResponder 时向下滚动

    // Call this method somewhere in your view controller setup code.
    - (void)registerForKeyboardNotifications
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification 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:UIKeyboardFrameEndUserInfoKey] 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;
        // Wouldn't go true so used an array that contains text fields that need to be scrolled   to
        //    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];
        //    }
        if ([self.scrollToObjects containsObject:self.activeField]) {
            CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y+    (self.activeField.frame.size.height*2)-kbSize.height);
            [self.scrollView setContentOffset:scrollPoint animated:YES];
        }
    }
    
    // Called when the UIKeyboardWillHideNotification is sent 
    - (void)keyboardWillBeHidden:(NSNotification*)aNotification
    { 
        // self.scrollView.contentInset = UIEdgeInsetsZero;
        [self.scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
        self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }
    

    更简单的解决方案是使用以下代码或类似于激活和停用对象的代码来处理下面的 UITextFieldDelegate 方法

    -(void)textFieldDidBeginEditing:(UITextField *)textField
    {
        CGPoint scrollPoint = CGPointMake(0.0, textField.frame.origin.y);
        [self.theScrollView setContentOffset:scrollPoint animated:YES];
    }
    
    -(void)textFieldDidEndEditing:(UITextField *)textField
    {
        [self.theScrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
        self.theScrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
    }
    

    【讨论】:

      【解决方案2】:

      我会检查你的增量计算。

      CGSize delta = CGSizeMake(self.frame.size.width - oldFrame.size.width,
                                    self.frame.size.height - oldFrame.size.height);
      

      我的猜测是 oldFrameself.frame 可能具有相同的尺寸。

      我正在尝试考虑是否还有其他可能遗漏的内容,例如将视图正确链接到这些对象或界面编辑器中的某些内容?

      【讨论】:

        【解决方案3】:

        问题出在keyboardSizeChanged:-您要调整的是frame.origin.y,而不是frame.size.height。至少希望它这样做。

        【讨论】:

          【解决方案4】:

          你也可以试试另一个库,它叫做TPKeyboardAvoiding。它工作得很好,而且很容易设置:

          1. 将 UIScrollView 添加到视图控制器的 xib 中
          2. 将滚动视图的类设置为 TPKeyboardAvoidingScrollView(仍然 在 xib 中,通过身份检查器)
          3. 将所有控件放在该滚动视图中

          它还会自动连接键盘上的“下一步”按钮来切换文本字段。

          【讨论】:

            猜你喜欢
            • 2018-12-16
            • 2011-07-10
            • 2014-11-23
            • 2015-05-31
            • 2018-05-21
            • 1970-01-01
            • 2015-10-19
            相关资源
            最近更新 更多