【问题标题】:TextField moves up when keyboard appears and scrolling enabled当键盘出现并启用滚动时,TextField 向上移动
【发布时间】:2015-08-17 10:30:36
【问题描述】:

我正在使用带有滚动视图的文本字段。每当出现键盘时,就会启用滚动并且文本字段会向上移动。但是有一个问题,如果我滚动我的文本字段,然后单击另一个文本字段,它不会向上移动。

请提出建议。

【问题讨论】:

  • 贴一些代码。你是怎么做的。
  • 试试 TPKeyboardAvoidingScrollView... 这将处理所有事情。 :)

标签: ios uiscrollview uitextfield


【解决方案1】:

如果您使用的是 scrollView ,这将是最适合您的。使用TPKeyboardAvoiding。它非常易于使用。

TPKeyboardAvoidingScrollView.mTPKeyboardAvoidingScrollView.h 源文件拖放到您的项目中,将UIScrollView 弹出到您的视图控制器的xib 中,将滚动视图的类设置为TPKeyboardAvoidingScrollView,然后将所有控件放在该滚动视图中。您也可以通过编程方式创建它,而无需使用 xib - 只需使用 TPKeyboardAvoidingScrollView 作为您的顶级视图。

【讨论】:

    【解决方案2】:

    您可以将文本字段坐标系转换为滚动视图坐标系。使用下面的代码

    -(void)rearrangeView{
        // previous
    
        if (txtActiveField == txtUsername) {
            CGPoint pt;
            CGRect rc = [txtUsername bounds];
            rc = [txtUsername convertRect:rc toView:scrollViewLogin];
            pt = rc.origin;
            pt.x = 0;
            pt.y -= 40;
            [scrollViewLogin setContentOffset:pt animated:YES];
        }
        else if (txtActiveField == txtPassword) {
            // [self.txtEmail becomeFirstResponder];
            CGPoint pt;
            CGRect rc = [txtPassword bounds];
            rc = [txtPassword convertRect:rc toView:scrollViewLogin];
            pt = rc.origin;
            pt.x = 0;
            pt.y -= 40;
            [scrollViewLogin setContentOffset:pt animated:YES];
        }
    }
    
    #pragma mark- UITextField Delegate
    -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
    {
        txtActiveField = textField;
        //txtActiveField.placeholder = @"";
        [self rearrangeView];
    
        return YES;
    }
    

    这里的 txtActiveField 是 UItextField 类型的实例变量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 2020-01-18
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 2014-12-09
      相关资源
      最近更新 更多