在指定的文本字段

时间:2015-07-07 22:06:30

标签: ios iphone swift

我的应用程序中有注册表单。它有大约7个用户填写的字段。 键盘下有些字段。

键盘隐藏了最后3个文本字段 - 所以我想只为它们移动框架。 我认为移动文本字段是个坏主意,因为我不仅应该移动文本字段,还要移动每个文本字段的标签。 我对视图底部没有约束。我的所有元素都与顶部元素的垂直间距是这个视图。

怎么做?

我认为它很明显且易于解决但却找到了许多建议(这些建议都没有对我有用)。

2 个答案:

答案 0 :(得分:0)

我认为您可以创建一个UIView,并将所有控件(textFields和标签)放在视图的顶部。 然后,只要用户点击将被键盘隐藏的textFields,您就可以将UIView的“contentInset”值设置为适当的值。 例如: self.palletView.contentInset = UIEdgeInsetsMake(-kKeyboardHeight,0,-kKeyboardHeight,0);

答案 1 :(得分:0)

我建议为事件UIKeyboardWillChangeFrameNotificationUIKeyboardWillHideNotification添加通知观察器,然后相应地更新您的视图约束。以下示例在Obj-C而不是Swift中,但您明白了这一点:

在你的控制器viewDidLoad中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

并在控制器中实现以下方法:

- (void)keyboardWillShow:(NSNotification *)notification {
    if (self.presentedViewController) return;

    NSDictionary *info = [notification userInfo];
    NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardFrame = [kbFrame CGRectValue];

    CGFloat height = keyboardFrame.size.height;

    // Update constraints here

    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}


- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    // Update constraints here

    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

这将使用键盘动画及时对约束的更改进行动画处理。在keyboardWillShow方法中,height是键盘完成显示时的高度,因此您可以从视图高度中减去此值以获得可见区域高度。

由于视图顶部只有约束,因此您可能还希望在视图底部添加一个优先级较低的视图。使这些约束IBOutlets并更新其常量和/或根据需要设置活动/非活动。 (注意:不要尝试更新优先级,否则会发生不好的事情。)

如果您有太多文本字段无法放入可查看区域但希望将它们全部显示,您可以考虑将它们放在UIScrollView或UITableView中,并相应地调整这些视图的约束。

相关问题