键盘可见的 UIScrollView

UIScrollView with keyboard visible

我有一个 UITextView(也是一个 UIScrollView),其中包含一堆文本。在屏幕截图中,键盘下方 有更多文本。我无法向上滚动查看该文本 - 无论我做什么,该文本仍保留在键盘下方。

我该如何解决才能滚动查看所有文本?

scrollView 有一个名为 contentSize 的 属性,它决定了用户可以滚动到的区域。您必须手动更改此值以补偿由于键盘造成的额外滚动 space。

我建议注册通知 UIKeyboardWillHideNotification UIKeyboardWillShowNotification.

当键盘即将显示时,触发UIKeyboardWillShowNotification通知,并在相应的方法中将键盘高度添加到滚动contentSize高度。

同样,从 UIKeyboardWillHideNotification 通知中的滚动 contentSize 高度中减去此高度。

希望对您有所帮助! :)

为避免所有手动调整大小等操作,我建议使用这个很棒的库 - https://github.com/hackiftekhar/IQKeyboardManager。它会为你完成所有艰苦的工作。

这行得通而且非常简单。

在.h

@property (weak, nonatomic) IBOutlet UITextView *tv;
@property CGSize keyboardSize;

在.m

- (void)viewDidLoad {
[super viewDidLoad];

// Register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void) keyboardWillShow: (NSNotification*) aNotification {

// Get the keyboard size from the notification userInfo
NSDictionary *info = [aNotification userInfo];
self.keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

// Adjust the content inset from the bottom by the keyboard's height
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, self.keyboardSize.height, 0);
self.tv.contentInset = contentInsets;
}

- (void) keyboardWillHide: (NSNotification*) aNotification {

// Reset the content inset when the keyboard is dismissed
self.tv.contentInset = UIEdgeInsetsZero;
}