我已经尝试了一些现有的解决方案,但它们无法按照我需要的方式工作。
我有一个很长的文本字段,里面有几个段落。当用户点击文本字段时,他们的键盘会弹出并基本上阻止大约一半已经存在的文本,并且键盘会阻止他们对文本字段进行任何添加,因为用户看不到他们正在输入的内容。
我已经尝试修改框架定义使其位于键盘上方,但由于文本字段太长,如果用户添加足够的文本,他们仍然可以位于键盘下方。将 TextView 包裹在 ScrollView 中也无济于事。
我正在使用 swift + xcode 6
这是我正在谈论的内容的屏幕截图:
最佳答案
假设您使用的是自动版式,您可以执行以下操作:
在.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];
}];
}
然后将 keyboardHeight
与 UITextView
和 View 底部之间的垂直自动布局约束链接起来:
关于ios - 键盘与 TextView 重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25428997/