我已经尝试了一些解决方案,但它们并没有按照我需要的方式发挥作用。
我有一个相当长的文本字段,里面会有几个段落。当用户点击文本字段时,他们的键盘弹出,基本上阻止了已经存在的大约一半的文本,并且键盘阻止他们对文本字段进行任何添加,因为用户看不到他们正在键入的内容。
我尝试修改框架定义以位于键盘上方,但由于文本字段太长,如果用户添加足够的文本,他们仍然可以转到键盘下方。将文本视图包装在滚动视图中也没有多大作用。
我使用的是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
和视图底部之间的垂直自动布局约束链接:
侦听 UIKeyboardWillShowNotification
和 UIKeyboardWillHideNotification
以根据需要调整文本视图的大小。您可以通过用户字典的UIKeyboardFrameEndUserInfoKey
获取键盘的尺寸。
例如。Apple代码的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)
}
}