【问题标题】:How to detect only when keyboard is being shown?如何仅在显示键盘时检测?
【发布时间】:2013-08-05 16:47:50
【问题描述】:

我希望我的 UIView 在显示键盘时动画到一个新位置,所以使用了UIKeyboardWillShowNotification 和UIKeyboardWillChangeFrameNotification。问题是,当设备在没有键盘的情况下旋转时,视图会自动调整大小并按应有的方式旋转 - 它看起来很完美。

不幸的是,在显示键盘的情况下,旋转设备会发送这些通知,因此执行 UIView 动画作为响应会给它一个奇怪的动画。最好将其描述为看起来像是跳到了一个新位置,然后被一个角锚定到新的方向。也许你知道我在说什么。

我有什么方法可以检测设备何时旋转或在显示键盘时旋转时处理问题?

【问题讨论】:

  • 旋转设备时是否发送 UIKeyboardWillShowNotification?您可以使用 UIKeyboardDidShowNotification 而不是使用 UIKeyboardWillChangeFrameNotification ,因此它不应该在旋转时发送。正如方法的名称所说,在设备旋转时发送 UIKeyboardWillChangeFrameNotofication 是正常的(因为框架已更改)。

标签: iphone ios objective-c uiview rotation


【解决方案1】:

对于方向变化检测,请使用UIDeviceOrientationDidChangeNotification。

【讨论】:

  • 只有在它发生之后才会被调用。太晚了——动画已经发生了。如果有 WillChangeNotification,并且在键盘之前调用它,那就完美了。
【解决方案2】:

我想下面的代码会对你有所帮助..

@property(nonatomic,strong)BOOL keyBoardShow;


- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];


    [super viewDidLoad];
}
-(void)keyboardWillBeShown:(NSNotification *)aNotification {
    keyBoardShow = YES;
}


-(void)keyboardWillBeHidden:(NSNotification *)aNotification {
    keyBoardShow = NO;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (keyBoardShow) {
        // Do the needful when the keyboard is shown

    }else{

    }
}

只需在keyboardWillBeShown 和keyboardWillBeHidden 委托方法中设置bool 值。并在 willRotateToInterfaceOrientation 中做你的 uiview 位置。

【讨论】:

    【解决方案3】:

    您为什么不依赖于内置通知,而不是依赖于首先触发键盘显示的原因?我猜当特定的 UITextField 成为第一响应者时,键盘会弹出。你应该可以使用它。

    为该 UITextField 注册一个委托并实现 -textFieldDidBeginEditing:。委托应该是一个视图控制器。然后,为了保持松散耦合,请发布您自己的委托通知并为此注册您的视图。

    这需要更多的工作,但它可以让您更好地控制。

    - (void)textFieldDidBeginEditing:(UITextField *)textField  
    

    Apple documentation: UITextFieldDelegate Protocol

    【讨论】:

    • 通过收听此委托调用,无法检索键盘外观动画详细信息。如果您想使用键盘为您的内容设置动画 - 这是最好的用户体验 - 您必须收听 UIKeyboard... 通知并从通知的 userInfo 字典中获取外观详细信息。
    猜你喜欢
    • 2011-05-21
    • 2017-01-29
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多