【问题标题】:Move UIView when Keyboard Appears键盘出现时移动 UIView
【发布时间】:2013-05-21 01:39:53
【问题描述】:

我有两个 UITextView,一个在 UIView 的顶部,另一个在 UIView 的底部。

我使用这段代码,在键盘出现时移动 UIView。

  - (void) viewDidLoad
{

[[NSNotificationCenter defaultCenter] addObserver:self
                                selector:@selector(keyboardWillShow)
                                    name:UIKeyboardWillShowNotification
                                  object:nil];

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

}


-(void)keyboardWillShow {
    // Animate the current view out of the way
    [UIView animateWithDuration:0.3f animations:^ {
        self.frame = CGRectMake(0, -160, 320, 480);
    }];
}

-(void)keyboardWillHide {
    // Animate the current view back to its original position
    [UIView animateWithDuration:0.3f animations:^ {
        self.frame = CGRectMake(0, 0, 320, 480);
    }];
}

当我从底部使用 UITextView 时效果很好。但我的问题是,当我想从 UIView 顶部使用 UITextView 时,键盘出现,UIView 向上移动,但我的顶部 UITextView 也向上移动。请帮助我,如果用户想从顶部在 UITextView 上键入文本,我不想移动 UIView。

【问题讨论】:

    标签: ios objective-c uiview uitextview


    【解决方案1】:

    我在项目中使用的一个非常简单的方法是 TPKeyboardAvoiding 库。

    https://github.com/michaeltyson/TPKeyboardAvoiding

    下载源代码,将 4 个文件放入您的项目中。在 InterfaceBuilder 中确保您的 TextViews 在 UIScrollView 或 UITableView 内,然后将该滚动视图或 tableview 的类更改为 TPAvoiding 子类。

    如果您不想这样做,您的另一个选择是检查正在使用哪个 TextView,并且仅在您想要的键盘是选定的键盘时才进行动画处理,即:

    -(void)keyboardWillShow {
        // Animate the current view out of the way
       if ([self.textFieldThatNeedsAnimation isFirstResponder]) {
            [UIView animateWithDuration:0.3f animations:^ {
            self.frame = CGRectMake(0, -160, 320, 480);
            }];
            self.animated = YES;
        }
    }
    
    -(void)keyboardWillHide {
        // Animate the current view back to its original position
        if (self.animated) {
          [UIView animateWithDuration:0.3f animations:^ {
              self.frame = CGRectMake(0, 0, 320, 480);
          }];
          self.animated = NO;
        }
    }
    

    【讨论】:

    • 很好的答案。非常感谢。这么简单,这么快。我喜欢它。
    • 这很好用,除非您试图减少应用程序的内存占用。请注意,将子视图添加到 UIScrollView 的成本很高,并且会显着增加内存使用量。
    • 好点,如果您不希望像我的回答中提到的那样手动为您的视图设置动画(尽管如果您使用自动布局,代码会有所不同)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    相关资源
    最近更新 更多