【问题标题】:Keyboard overlaps Text View键盘重叠文本视图
【发布时间】:2014-08-21 22:52:07
【问题描述】:

我已经尝试了一些现有的解决方案,但它们并没有按照我需要的方式工作。

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

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

我正在使用 swift + xcode 6

这是我正在谈论的屏幕截图:

【问题讨论】:

  • 您可以使用NSLayoutConstraint 来调整 UITextView 框架的大小。

标签: ios xcode swift


【解决方案1】:

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

在.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 和视图底部之间的垂直自动布局约束链接:

【讨论】:

  • 这与我推荐的方法相同。
  • 我提到我在问题中使用的是 Swift + xcode 6,但无论如何谢谢。
【解决方案2】:

收听UIKeyboardWillShowNotificationUIKeyboardWillHideNotification 以适当调整文本视图的大小。您可以通过用户字典的UIKeyboardFrameEndUserInfoKey 获取键盘的尺寸。

例如Apple's code 的 Swift 版本:

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)
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多