我设置滚动视图偏移以显示被键盘隐藏的文本字段。如果用户在显示键盘时滚动,则滚动视图会向下捕捉
Posted
技术标签:
【中文标题】我设置滚动视图偏移以显示被键盘隐藏的文本字段。如果用户在显示键盘时滚动,则滚动视图会向下捕捉【英文标题】:I set scroll view offset to show text field hidden by keyboard. If the user scrolls while keyboard is show, scroll view snaps back down 【发布时间】:2015-09-02 07:53:12 【问题描述】:正如标题所说,我在 UIScrollView 中有一个 UITextField。显示键盘时,我调整滚动视图的 contentOffset 以便隐藏文本字段。问题是文本字段是否位于滚动视图的底部。当键盘弹出时,滚动视图会根据需要进行调整。但是,如果用户触摸并滚动键盘上方的区域,则滚动视图会向下捕捉。直观地说,这是有道理的,因为我以编程方式过度滚动了滚动视图,但从用户的角度来看,这并不好。
对此我能做些什么?我想到的一件事是移动整个滚动视图框架而不是设置内容偏移量。我不知道该怎么做。我在 CGFloat 中存储了所需的偏移量变化。有人可以帮忙吗?
【问题讨论】:
【参考方案1】:您需要更改contentInset
。 contentOffset
是当前滚动位置,因此当用户滚动时它会被重置。
可以在这里找到一个例子:https://***.com/a/16806736/78496
【讨论】:
你能举个例子吗?【参考方案2】:您可以做的一件事是收听UIKeyboardWillShowNotification
和UIKeyboardWillHideNotification
系统通知,以了解何时修改UIScrollView 的contentInset
。你可以在viewWillAppear:
- (void)viewWillAppear:(BOOL)animated
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
别忘了把自己也去掉观察者的身份,
- (void)viewWillDisappear:(BOOL)animated
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
当键盘显示或隐藏时,您可以根据键盘的高度调整contentInset
。
- (void)keyboardWillShow:(NSNotification *)notification
CGRect keyboardEndFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIEdgeInsets scrollInsetWithKeyboard = UIEdgeInsetsMake(0, 0, 0, -keyboardEndFrame.height, 0)
self.scrollView.contentInset = scrollInsetWithKeyboard; // If you have a custom inset maybe now would be a good idea to save it so you can restore it later
- (void)keyboardWillHide:(NSNotification *)notification
self.scrollView.contentInset = UIEdgeInsetsZero; // Or to whatever inset you had before
当这两种方法被触发时,如果您愿意,您还可以为 contentOffset
设置动画。
【讨论】:
【参考方案3】:你应该使用这个库:https://github.com/hackiftekhar/IQKeyboardManager
真是太棒了,你只需要在你的项目中添加这个库,它就会管理你所有的文本字段。你有零行代码来实现这个库,它是自动的。我在我的所有项目中都使用它,它在任何地方都可以正常工作(对于单元格中的文本字段、表格视图、滚动视图......)
【讨论】:
以上是关于我设置滚动视图偏移以显示被键盘隐藏的文本字段。如果用户在显示键盘时滚动,则滚动视图会向下捕捉的主要内容,如果未能解决你的问题,请参考以下文章
iOS 如何在滚动视图/webview 上实现点击手势以“敲出”文本字段?