与键盘一起移动的视图

时间:2013-10-29 07:30:12

标签: ios iphone uiscrollview ios7 autolayout

我有一个带有UIScrollView的iOS应用,它基本上看起来像屏幕上的Messages.app:内容,底部是文本视图和添加更多内容的按钮。当键盘出现时,文本视图和按钮正确向上移动。

我已设置keyboardDismissMode,以便向下拖动键盘使其消失,但在拖动过程中,当键盘向下移动时,如何在屏幕上更新我的视图位置以保持连接它?看来键盘会改变帧通知在此过程中不会被触发。

这样做的“正确”方法是什么?

编辑:我有一种预感,使用输入视图/配件视图可能是可行的,但不确定这是正确的方向。

2 个答案:

答案 0 :(得分:1)

非常确定这种行为需要SPI。但是:您可以遍历视图/窗口层次结构,找到键盘窗口,并对其应用变换以在交互过程中移动它。 ( window.transform =

不确定当你的交互结束时该怎么做 - 也许可以手动设置键盘的动画(使用上述技术)来完成键盘隐藏,然后当它被隐藏时,在没有动画的情况下重新启动第一响应者。

编辑:

抱歉,我以为你想移动键盘,但是如果你想观察键盘的位置,可以使用KVO(如@KudoCC建议的那样)

static void * __keyboardCenterKVOContext = & __keyboardCenterKVOContext ;

-(void)setUpKeyboardObserver
{
    UIView * keyboardView = ...?
    [ keyboardView addObserver:self forKeyPath:@"center" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:__keyboardCenterKVOContext ] ;
}

然后实施KVO观察员:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ( context == __keyboardCenterKVOContext )
    {
        CGPoint newKeyboardCenter = [ [ change valueForKey:NSKeyValueChangeNewKey ] pointValue ] ;
        // .. handle new keyboard position here ...
    }
    else
    {
        [ super observeValueForKeyPath:keyPath ofObject:object change:change context:context ] ;
    }
}

每次键盘视图更改其中心属性时,都会运行KVO观察器。您也可以尝试观察键盘窗口的frame和/或transform属性。

我有一些代码可以帮助您进行KVO观察,这可能会对您有所帮助:https://gist.github.com/nielsbot/6873377

(您可能想要使用我的帮助程序代码的原因是因为它会自动从正被释放的对象中删除KVO观察。这需要一些运行时间,但在您的情况下,您实际上并不知道键盘窗口何时会要解除分配。虽然你可以在你的keyboardWillHide处理程序中拆掉KVO)

答案 1 :(得分:0)

当键盘消失并显示时,您可以尝试通知移动内容:

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(keyboardDisappeared) name:UIKeyboardWillHideNotification object:nil];
    [center addObserver:self selector:@selector(keyboardAppeared) name:UIKeyboardWillShowNotification object:nil];


    -(void) keyboardDisappeared
    {
     [UIView animateWithDuration:1.0 delay:0 options:yourAnimationOption  animations:^
            {
                   self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+100(same as you do in keyboardAppeared), self.view.frame.size.width, self.view.frame.size.height);

            } completion::^(BOOL finished) 
                 {
               }];
    }

 -(void) keyboardAppeared
    {
     [UIView animateWithDuration:1.0 delay:0 options:yourAnimationOption  animations:^
            {
                   self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y-(as much you want), self.view.frame.size.width, self.view.frame.size.height);

            } completion::^(BOOL finished) 
                 {
               }];
    }
相关问题