【问题标题】:Is there a recommended or even automatic way to move a UITextField into view when editing it?在编辑 UITextField 时,是否有推荐的甚至自动的方法将其移动到视图中?
【发布时间】:2012-06-14 13:55:47
【问题描述】:

现在已经以各种方式实现了这一点,我想知道:如果从UITextField 开始编辑并出现键盘,是否有推荐的甚至自动化的方法可以通过向上滚动来保持文本字段可见? 我认为向上滚动整个根视图是最简单和最好的。到目前为止,我在 API 中是否缺少某些东西,可以避免我自己编写这段代码?

【问题讨论】:

标签: objective-c ios uikit uitextfield


【解决方案1】:

我将所有 UITextFields 都放在 contentView 上(在我的示例中,我将此视图称为“movableView”),然后当用户点击其中一个文本字段时

//The hardcoded 10's and 20's are the origin of the view before
//the user starts messing with it! 

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    [self scrollViewToTextField:textField];
    //Other stuff I want to do here
    return YES;
}

- (void)scrollViewToTextField:(id)textField
{
    UITextField* tf = (UITextField*)textField;

    CGPoint newOffset = tf.frame.origin;
    newOffset.x = 10;
    newOffset.y = 20 - newOffset.y;

    //This is a category method on UIView which simply adjusts the views
    //frame over a delay.
    [self.movableView moveToX:newOffset.x andY:newOffset.y withDuration:0.3f];
}

编辑完成后,您必须将视图移回

-(void)textFieldDidEndEditing:(UITextField *)textField {

    [self resetView];
    // do other stuff here such as grab the text and stick it in ivars etc.

}

-(void)resetView {
    [self.movableView moveToX:10.0f andY:10.0f withDuration:0.3f];
}

以防万一 - 这是完整性的类别方法

//  UIView+BasicAnimation.h
-(void) moveToX:(CGFloat) x andY:(CGFloat) y withDuration:(NSTimeInterval) duration;


//  UIView+BasicAnimation.m
-(void) moveToX:(CGFloat) x andY:(CGFloat) y withDuration:(NSTimeInterval) duration {
    CGRect newFrame = self.frame;
    newFrame.origin.x = x;
    newFrame.origin.y = y;

    [UIView beginAnimations:@"BasicAnimation" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:duration];

    self.frame = newFrame;

    [UIView commitAnimations];
}

【讨论】:

  • 我使用几乎完全相同的格式,效果很好,一旦实施,以后添加多个文本视图非常容易。
【解决方案2】:

我认为不存在任何这样的事情,这似乎是一个奇怪的遗漏。当您考虑 iPad 分体键盘的存在时,它似乎更像是一次应该正确完成并在 API 中提供的东西。

对于当前项目,我正在尝试TPKeyboardAvoidingScrollView。 (https://github.com/michaeltyson/TPKeyboardAvoiding)

【讨论】:

    【解决方案3】:

    通常通过使用UIScrollView 并在字段获得 firstResponder 状态时修改内容偏移量来实现这一点。

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2011-02-03
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多