键盘存在时 UIViewController 向上移动

Posted

技术标签:

【中文标题】键盘存在时 UIViewController 向上移动【英文标题】:UIViewController move up when keyboard present 【发布时间】:2014-04-29 04:02:16 【问题描述】:

我有一个带有文本字段的 uiviewcontroller。单击底部文本字段时,该字段被键盘覆盖,当您单击文本字段时,如何使其“向上滚动”。或者只是拥有它,以便 uiviewcontroller 可以滚动

【问题讨论】:

Google“当键盘出现时 UIViewController 向上移动” 【参考方案1】:

尝试将视图的所有文本字段放在滚动视图中,然后使视图控制器符合 UITextFieldDelegateUINavigationControllerDelegate

在 viewController.m 中定义以下方法

-(IBAction)textFieldDidBeginEditing:(UITextField *)sender // connect all textfields in your view to this method

    sender.delegate = self;

//called when UIKeyboardDidShowNotification is sent.
-(void)keyboardWasShown:(NSNotification *)aNotification

    NSDictionary * info =   [aNotification userInfo];
    CGSize  kbSize  =   [[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;
    [self.scrollView setContentOffset:CGPointMake(0, kbSize.height) animated:YES];


// Called when the UIKeyboardWillHideNotification is sent,method is called when the keyboard is closed. It returns the scroll view to its original position.
- (void)keyboardWillBeHidden:(NSNotification*)aNotification

    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];


//This method is called when you have finished editing a text field.
- (BOOL)textFieldShouldReturn:(UITextField *)textField 
    return [textField resignFirstResponder];

把它放在你的 viewDidLoad 中:

- (void)viewDidLoad

    [super viewDidLoad];        
    // Do any additional setup after loading the view.
    self.scrollView.scrollEnabled = YES;
    self.automaticallyAdjustsScrollViewInsets = YES;

这可能会奏效...... HTH :)

【讨论】:

以上是关于键盘存在时 UIViewController 向上移动的主要内容,如果未能解决你的问题,请参考以下文章

当键盘出现在 iOS8 的 iPad 上时,向上移动模态呈现的 UIViewController

显示键盘时,自定义 UIView 正在向上推部分内容

键盘显示时在 UIViewController 中设置 Tableview y 位置

显示软键盘时向上移动布局?

键盘出现多次时,滚动视图不会向上移动

出现软键盘时工具栏向上移动