键盘隐藏视图(AutoLayout + StoryBoard)

时间:2015-09-16 12:30:25

标签: ios autolayout xcode-storyboard

对这个基本问题抱歉,我是iOS开发的新手。我在带有AutoLayout的View中有一个UITextField,我想用它来键入聊天系统的消息。但是,当显示键盘时,它会隐藏包含UITextField的视图(整个视图位于键盘后面)。

当键盘从底部过渡时,应该如何将视图与键盘一起移动?当键盘被解除时,UIView应该回到其原始位置(在屏幕的底部)。 我的整个用户界面都是在故事板中使用AutoLayout设计的。

编辑: 我向How do I scroll the UIScrollView when the keyboard appears?查找了一个解决方案,但似乎没有任何迹象表明AutoLayout已在此答案中的约束条件下使用。如何在Storyboard中使用AutoLayout实现同样的目标。再次,对于任何缺乏理解的道歉,因为我对iOS开发很新。

2 个答案:

答案 0 :(得分:0)

将UIScrollView添加到视图控制器,并将UITextField保持在scrollview上。

添加UITextFieldDelegate

yourTextField.delegate = self;

您可以在触摸UITextField时设置scrollview的内容偏移量,并在键盘辞职时将其重新定位到(0,0)。

-(void)viewWillAppear:(BOOL)animated
{
yourScrollView.contentSize = CGSizeMake(320, 500);

[super viewWillAppear:YES];

}

-(void)textFieldDidBeginEditing:(FMTextField *)textField
{
    [yourScrollView setContentOffset:CGPointMake(0,textField.center.y-140) animated:YES];//you can set your  y cordinate as your req also
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
     [textField resignFirstResponder];
     [yourScrollView setContentOffset:CGPointMake(0,0) animated:YES];
    return YES;
} 

答案 1 :(得分:0)

这是我最近所做的,可能会有所帮助。

我的所有字段都在一个带有顶部约束的包装器视图中。因为对我来说,移动包装器视图上下几个像素就足够了我使用这种方法。 Here是一个滚动视图示例。

我使用IBOutlet来引用此约束

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //register for keyboard notifications
    _keyboardIsShowing = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

然后关于通知方法

  #pragma mark - Keyboard notifications methods
    - (void)keyboardWillShow:(NSNotification *) notification{

        if (!_keyboardIsShowing) {
            _keyboardIsShowing = YES;
            [UIView animateWithDuration:0.4 animations:^{
//here update the top constraint to some new value
                _topConstraint.constant = _topConstraint.constant - 30;
                [self.view layoutIfNeeded];
            }];
        }
    }

    - (void)keyboardWillHide:(NSNotification *) notification{
        if (_keyboardIsShowing) {
            [UIView animateWithDuration:0.4 animations:^{
                _topConstraint.constant = _topConstraint.constant + 30;
                [self.view layoutIfNeeded];
            }];

            _keyboardIsShowing = NO;
        }
    }

这里有很多这样的答案。 祝你好运。

相关问题