代码之家  ›  专栏  ›  技术社区  ›  Mikeware

uikeyboardBoundsUserInfoKey已弃用,改为使用什么?

  •  49
  • Mikeware  · 技术社区  · 16 年前

    我正在使用3.2sdk开发iPad应用程序。我正在处理获取键盘大小以防止我的文本字段隐藏在它后面。

    我在Xcode中收到警告->uikeyboardBoundsUserInfoKey已被弃用。我应该使用什么来代替不获取此警告?

    9 回复  |  直到 7 年前
        1
  •  87
  •   Burak    14 年前

    我使用了之前提供的解决方案,但仍然存在问题。我想到的是:

        - (void)keyboardWillShow:(NSNotification *)aNotification {
        [self moveTextViewForKeyboard:aNotification up:YES];
    }
    
        - (void)keyboardWillHide:(NSNotification *)aNotification {
            [self moveTextViewForKeyboard:aNotification up:NO]; 
        }
    
    - (void) moveTextViewForKeyboard:(NSNotification*)aNotification up: (BOOL) up{
    NSDictionary* userInfo = [aNotification userInfo];
    
    // Get animation info from userInfo
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    
    
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
    
    // Animate up or down
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    
    CGRect newFrame = textView.frame;
    CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];
    
    newFrame.origin.y -= keyboardFrame.size.height * (up? 1 : -1);
    textView.frame = newFrame;
    
    [UIView commitAnimations];
    }
    
        2
  •  55
  •   Alex Reynolds    14 年前

    从 documentation 对于 UIKeyboardBoundsUserInfoKey :

    NSVALUE对象的键,该对象包含一个CGRECT,该CGRECT在窗口坐标中标识键盘的边界矩形。这个值足以获得键盘的大小。如果要在屏幕上获取键盘的原点(动画之前或之后),请使用从用户信息字典通过uikeyboardcenterbeginoserinfokey或uikeyboardcenterenduserinfokey常量获得的值。 请改用uikeyboardframebeginserinfo键或uikeyboardframeenduserinfokey键。

    苹果建议实现这样一个方便的例行程序(它可以作为一个类别添加到 UIScreen ):

    + (CGRect) convertRect:(CGRect)rect toView:(UIView *)view {
        UIWindow *window = [view isKindOfClass:[UIWindow class]] ? (UIWindow *) view : [view window];
        return [view convertRect:[window convertRect:rect fromWindow:nil] fromView:nil];
    }
    

    恢复窗口调整的键盘帧大小属性。

    我采用了另一种方法,包括检查设备方向:

    CGRect _keyboardEndFrame;
    [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&_keyboardEndFrame];
    CGFloat _keyboardHeight = ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) ? _keyboardEndFrame.size.height : _keyboardEndFrame.size.width;
    
        3
  •  9
  •   sth    15 年前

    您只需使用以下代码:

    //NSVale *aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    //instead of Upper line we can use either next line or nextest line.
    //NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    
        4
  •  3
  •   Community Mohan Dere    9 年前

    以下代码修复了 Jay's answer ,假设 UIKeyboardWillShowNotification 当键盘已经存在时,不会再次激发。

    用日文/中文键盘打字时,iOS会额外启动一个 ui键盘将显示通知 使用新的键盘框架,即使键盘已经存在,也会导致 self.textView 在原始代码中第二次减少。

    这减少了 文本视图 几乎什么都没有。这样一来,我们就不可能从这个问题中恢复过来,因为我们只期望一个 UIKeyboardWillHideNotification 下次键盘关闭时。

    而不是减去/增加高度 文本视图 根据键盘是否像原始代码一样显示/隐藏,以下代码只计算 文本视图 减去屏幕上键盘的高度后。

    这假设 文本视图 假设填充视图控制器的整个视图,并且没有其他需要可见的子视图。

    - (void)resizeTextViewWithKeyboardNotification:(NSNotification*)notif {
    
        NSDictionary* userInfo = [notif userInfo];
        NSTimeInterval animationDuration;
        UIViewAnimationCurve animationCurve;
        CGRect keyboardFrameInWindowsCoordinates;
    
        [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
        [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
        [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrameInWindowsCoordinates];
    
        [self resizeTextViewToAccommodateKeyboardFrame:keyboardFrameInWindowsCoordinates
                                 withAnimationDuration:animationDuration
                                        animationCurve:animationCurve];
    
    }
    
    - (void)resizeTextViewToAccommodateKeyboardFrame:(CGRect)keyboardFrameInWindowsCoordinates
                               withAnimationDuration:(NSTimeInterval)duration
                                      animationCurve:(UIViewAnimationCurve)curve
    {
    
        CGRect fullFrame = self.view.frame;
    
        CGRect keyboardFrameInViewCoordinates =
        [self.view convertRect:keyboardFrameInWindowsCoordinates fromView:nil];
    
        // Frame of the keyboard that intersects with the view. When keyboard is
        // dismissed, the keyboard frame still has width/height, although the origin
        // keeps the keyboard out of the screen.
        CGRect keyboardFrameVisibleOnScreen =
        CGRectIntersection(fullFrame, keyboardFrameInViewCoordinates);
    
        // Max frame availble for text view. Assign it to the full frame first
        CGRect newTextViewFrame = fullFrame;
    
        // Deduct the the height of any keyboard that's visible on screen from
        // the height of the text view
        newTextViewFrame.size.height -= keyboardFrameVisibleOnScreen.size.height;
    
        if (duration)
        {
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:duration];
            [UIView setAnimationCurve:curve];
        }
    
        // Adjust the size of the text view to the new one
        self.textView.frame = newTextViewFrame;
    
        if (duration)
        {
            [UIView commitAnimations];
        }
    
    }
    

    另外,不要忘记在viewdidload中注册键盘通知:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSNotificationCenter* notifCenter = [NSNotificationCenter defaultCenter];
    
        [notifCenter addObserver:self selector:@selector(resizeTextViewWithKeyboardNotification:) name:UIKeyboardWillShowNotification object:nil];
        [notifCenter addObserver:self selector:@selector(resizeTextViewWithKeyboardNotification:) name:UIKeyboardWillHideNotification object:nil];
    }
    

    关于将调整大小的代码拆分为两部分

    textView调整大小代码拆分为两部分的原因( resizeTextViewWithKeyboardNotification: 和 resizeViewToAccommodateKeyboardFrame:withAnimationDuration:animationCurve: )当键盘通过从一个视图控制器推到另一个视图控制器时,解决另一个问题(请参见 How do I detect the iOS keyboard when it stays up between controllers? )

    由于在按下视图控制器之前键盘已经存在,因此iOS不会生成其他键盘通知,因此无法调整 textView 基于这些键盘通知。

    调整大小的上述代码(以及原始代码) 文本视图 因此只有当显示键盘时才能工作 之后 视图已加载。

    我的解决方案是创建一个存储最后一个键盘坐标的单例 - viewDidAppear: 在ViewController中,调用:

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    
        // Resize the view if there's any keyboard presence before this
        // Only call in viewDidAppear as we are unable to convertRect properly
        // before view is shown
        [self resizeViewToAccommodateKeyboardFrame:[[UASKeyboard sharedKeyboard] keyboardFrame]
                             withAnimationDuration:0
                                    animationCurve:0];
    }
    

    UASKeyboard 我的单身汉在这儿吗?理想情况下我们应该打电话给 - viewWillAppear: 但是,根据我的经验(至少在iOS 6上), convertRect:fromView: 我们需要使用的方法 调整视图大小以适应常用键盘框架:带动画持续时间:动画曲线: 在视图完全可见之前,无法将键盘框架正确转换为视图坐标。

        5
  •  2
  •   BBog Smith    14 年前

    只使用 UIKeyboardFrameBeginUserInfoKey 或 UIKeyboardFrameEndUserInfoKey 而不是钥匙 UIKeyboardBoundsUserInfoKey

        6
  •  1
  •   Thomas    16 年前

    @杰森,你的代码如果可以的话,除了一点。

    现在,您实际上没有设置任何动画,视图只会“弹出”到新的大小和高度。

    您必须指定要从中进行动画制作的状态。动画是一种(从状态)->(到状态)的东西。

    幸运的是,有一种非常方便的方法可以将视图的当前状态指定为(从状态)。

    [UIView setAnimationBeginsFromCurrentState:YES];
    

    如果您在beginimations:context:之后添加这一行,您的代码就可以完美地工作。

        7
  •  1
  •   Cameron Lowell Palmer    15 年前
    - (CGSize)keyboardSize:(NSNotification *)aNotification {
        NSDictionary *info = [aNotification userInfo];
        NSValue *beginValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    
        CGSize keyboardSize;
        if ([UIKeyboardDidShowNotification isEqualToString:[aNotification name]]) {
            _screenOrientation = orientation;
            if (UIDeviceOrientationIsPortrait(orientation)) {
                keyboardSize = [beginValue CGRectValue].size;
            } else {
                keyboardSize.height = [beginValue CGRectValue].size.width;
                keyboardSize.width = [beginValue CGRectValue].size.height;
            }
        } else if ([UIKeyboardDidHideNotification isEqualToString:[aNotification name]]) {
            // We didn't rotate
            if (_screenOrientation == orientation) {
                if (UIDeviceOrientationIsPortrait(orientation)) {
                    keyboardSize = [beginValue CGRectValue].size;
                } else {
                    keyboardSize.height = [beginValue CGRectValue].size.width;
                    keyboardSize.width = [beginValue CGRectValue].size.height;
                }
            // We rotated
            } else if (UIDeviceOrientationIsPortrait(orientation)) {
                keyboardSize.height = [beginValue CGRectValue].size.width;
                keyboardSize.width = [beginValue CGRectValue].size.height;
            } else {
                keyboardSize = [beginValue CGRectValue].size;
            }
        }
    
    
        return keyboardSize;
    }
    
        8
  •  0
  •   karim    14 年前
        9
  •  0
  •   Mohammed Abunada    7 年前

    它的工作原理是这样的

    这是“保存”按钮底部的约束

    @IBOutlet weak var saveBtnBottom: NSLayoutConstraint!
    @IBOutlet weak var nameText: UITextField!
    

    内部视图加载

    NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    nameText.delegate = self
    

    这是我们需要的功能

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        nameText.resignFirstResponder()
        return true
    }
    
    
    @objc func keyBoardWillShow(notification: Notification){
        if let userInfo = notification.userInfo as? Dictionary<String, AnyObject>{
            let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey]
            let keyBoardRect = frame?.cgRectValue
            if let keyBoardHeight = keyBoardRect?.height {
                self.saveBtnBottom.constant = keyBoardHeight 
    
                UIView.animate(withDuration: 0.5, animations: {
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
    
    @objc func keyBoardWillHide(notification: Notification){
        self.saveBtnBottom.constant = 30.0
        UIView.animate(withDuration: 0.5, animations: {
            self.view.layoutIfNeeded()
        })
    }
    
    推荐文章