键盘重叠文本视图

时间:2014-08-21 14:28:43

标签: ios xcode swift

我已经尝试了一些解决方案,但它们并不像我需要的那样工作。

我有一个很长的文本字段,里面会有几个段落。当用户点击文本字段时,他们的键盘弹出并基本上阻止了已经存在的文本的大约一半,并且键盘阻止他们对文本字段进行任何添加,因为用户无法看到他们正在键入的内容。

我已经尝试修改框架定义以使其位于键盘上方,但由于文本字段太长,如果用户添加足够的文本,用户仍然可以进入键盘下方。在滚动视图中包装文本视图也没有太大作用。

我正在使用swift + xcode 6

以下是我所说的截图:

enter image description here

2 个答案:

答案 0 :(得分:9)

假设您正在使用自动布局,您可以执行以下操作:

在.h中,定义NSLayouConstraint

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

在.m:

- (void)viewDidLoad
{
    [super 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
{
    NSDictionary *info = [notification userInfo];
    NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardFrame = [kbFrame CGRectValue];

    self.keyboardHeight.constant = keyboardFrame.size.height;

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

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

    self.keyboardHeight.constant = 20;
    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

然后将keyboardHeightUITextView和视图底部之间的垂直自动布局约束相关联:

enter image description here

答案 1 :(得分:0)

聆听UIKeyboardWillShowNotificationUIKeyboardWillHideNotification,根据需要调整文字视图的大小。您可以通过用户词典的UIKeyboardFrameEndUserInfoKey获取键盘的尺寸。

E.g。一个Swift版本的Apple's code

func keyboardWasShown(aNotifcation: NSNotification) {

    let info = aNotifcation.userInfo as NSDictionary?
    let rectValue = info![UIKeyboardFrameBeginUserInfoKey] as NSValue
    let kbSize = rectValue.CGRectValue().size

    let contentInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0)
    textView.contentInset = contentInsets
    textView.scrollIndicatorInsets = contentInsets

    // optionally scroll
    let aRect = textView.superview!.frame
    aRect.size.height -= kbSize.height
    let targetRect = CGRectMake(0, 0, 10, 10) // get a relevant rect in the text view
    if !aRect.contains(targetRect.origin) {
        textView.scrollRectToVisible(targetRect, animated: true)
    }
}
相关问题