ios - 键盘与 TextView 重叠

标签 ios xcode swift

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

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

我已经尝试修改框架定义使其位于键盘上方,但由于文本字段太长,如果用户添加足够的文本,他们仍然可以位于键盘下方。将 TextView 包裹在 ScrollView 中也无济于事。

我正在使用 swift + xcode 6

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

enter image description here

最佳答案

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

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

enter image description here

关于ios - 键盘与 TextView 重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25428997/

相关文章:

ios - 调用嵌入式 containerVC 方法时不调用父 VC 委托(delegate)方法

c++ - XCode 9.3 升级或替换 libc++

ios - 按下按钮时滚动到特定的幻灯片/网站

iphone - 有没有其他方法可以使用动画 block 来执行此动画?

ios - 对于通知推送,真正的 iPhone 设备在 App 首次加载时不会显示 Approval Alert

ios - 为什么苹果App Store图标显示为白色

当我尝试添加配置文件时,iOS Provisioning Portal 出错

ios - 搜索栏文本字段颜色不会改变

ios - TableViewCells 数组在更新 TableView 后重新排序

ios - Xcode 8每次都重新编译完整代码