【问题标题】:How to move UITextField after keyboard appears?键盘出现后如何移动 UITextField?
【发布时间】:2015-06-26 03:05:23
【问题描述】:

我正在做一个小项目。它基本上只是一个文本字段,您可以在其中输入一些短文本(基本上只有几个单词),然后您在下面有 3 个主要按钮(它看起来像一个标签栏)您可以选择按键盘来更改文本或如果没有,请输入一个,您可以按颜色为文本选择不同的颜色,也可以按第三个按钮更改字体。

所以,我刚开始,我有一个问题,如果我按下键盘按钮,键盘应该出现,并且 textview 应该自动向上移动 216px(键盘的高度)我有以下代码:

frame.origin 中的 111 是它应该移动的 y 坐标。

- (IBAction)keyBoardAction:(id)sender {

CGRect frame = _textField.frame;
frame.origin.y = 111;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
_textField.frame = frame;
[UIView commitAnimations];

[_textField becomeFirstResponder];

}

因为它不起作用,所以我运行应用程序时没有将textField 设置为firstResponder,这样键盘就不会挡住我的视线,我可以在整个过程中看到 textField。

当我运行应用程序并按下键盘按钮时,textField 首先下降到屏幕下方,然后再次向上移动到与开始时相同的位置。

【问题讨论】:

    标签: ios objective-c keyboard


    【解决方案1】:
    - (void)registerNotifications
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
    
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }
    
    
    - (void) keyboardWillShow:(NSNotification *)notification
    {
        NSDictionary *userInfo = [notification userInfo];
    
        NSTimeInterval duration = userInfo ? [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue] : 1.0;
    
        CGRect keyboardEndFrame;
        [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
        CGRect newFrame = _textField.frame;
        newFrame.origin.y -= keyboardEndFrame.size.height;
    
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration: duration];
        _textField.frame = newFrame;
        [UIView commitAnimations];
    
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-19
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2015-03-22
      • 1970-01-01
      • 2013-05-21
      相关资源
      最近更新 更多