当键盘存在时,如何使 UITextField 向上移动 - 开始编辑?
使用 iOS SDK:
我有一个带有 UITextField
的 UIView,可以调出键盘。 我需要它能够:
允许滚动
UIScrollView
的内容,以便在键盘打开后查看其他文本字段自动“跳转”(通过向上滚动)或缩短
我知道我需要一个 UIScrollView。 我尝试将 UIView
的类更改为 UIScrollView
,但我仍然无法向上或向下滚动文本框。
我是否需要 UIView
和 UIScrollView
? 一个会进入另一个的内部吗?
需要实现什么才能自动滚动到活动文本字段?
理想情况下,尽可能多的组件设置将在 Interface Builder 中完成。 我只想为需要的地方编写代码。
注意:我正在使用的 UIView
(或 UIScrollView
)是由选项卡栏(UITabBar
)调出的,它需要充当普通的。
我只是在键盘出现时添加滚动条。 尽管不需要,但我觉得它提供了更好的界面,因为用户可以滚动和更改文本框等。
当键盘向上和向下移动时,我可以在更改 UIScrollView
的框架大小的地方使用它。 我只是使用:
-(void)textFieldDidBeginEditing:(UITextField *)textField {
//Keyboard becomes visible
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height - 215 + 50); // Resize
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
// Keyboard will hide
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height + 215 - 50); // Resize
}
但是,这不会自动“向上移动”或将下部文本字段置于可见区域的中心,而这正是我真正想要的。
With the iOS SDK:
I have a UIView
with UITextField
s that bring up a keyboard. I need it to be able to:
Allow scrolling of the contents of the
UIScrollView
to see the other text fields once the keyboard is brought upAutomatically "jump" (by scrolling up) or shortening
I know that I need a UIScrollView
. I've tried changing the class of my UIView
to a UIScrollView
, but I'm still unable to scroll the textboxes up or down.
Do I need both a UIView
and a UIScrollView
? Does one go inside the other?
What needs to be implemented in order to automatically scroll to the active text field?
Ideally as much of the setup of the components as possible will be done in Interface Builder. I'd like to only write code for what needs it.
Note: the UIView
(or UIScrollView
) that I'm working with is brought up by a tabbar (UITabBar
), which needs to function as normal.
I am adding the scroll bar just for when the keyboard comes up. Even though it's not needed, I feel like it provides a better interface because then the user can scroll and change textboxes, for example.
I've got it working where I change the frame size of the UIScrollView
when the keyboard goes up and down. I'm simply using:
-(void)textFieldDidBeginEditing:(UITextField *)textField {
//Keyboard becomes visible
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height - 215 + 50); // Resize
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
// Keyboard will hide
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height + 215 - 50); // Resize
}
However, this doesn't automatically "move up" or center the lower text fields in the visible area, which is what I would really like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
需要考虑的一件事是您是否想单独使用
UITextField
。 我还没有遇到过任何设计良好的 iPhone 应用程序在UITableViewCells
之外实际使用UITextFields
。这将是一些额外的工作,但我建议您将所有数据输入视图实现为表视图。 将
UITextView
添加到您的UITableViewCells
。One thing to consider is whether you ever want to use a
UITextField
on its own. I haven’t come across any well-designed iPhone apps that actually useUITextFields
outside ofUITableViewCells
.It will be some extra work, but I recommend you implement all data entry views a table views. Add a
UITextView
to yourUITableViewCells
.本文档详细介绍了以下问题的解决方案:这个问题。 查看“移动位于键盘下的内容”下的源代码。 这非常简单。
编辑:注意到示例中有一个小故障。 您可能想要监听
UIKeyboardWillHideNotification
而不是UIKeyboardDidHideNotification
。 否则,键盘后面的滚动视图将在键盘关闭动画期间被剪切。This document details a solution to this problem. Look at the source code under 'Moving Content That Is Located Under the Keyboard'. It's pretty straightforward.
EDIT: Noticed there's a wee glitch in the example. You will probably want to listen for
UIKeyboardWillHideNotification
instead ofUIKeyboardDidHideNotification
. Otherwise the scroll view behind of the keyboard will be clipped for the duration of the keyboard closing animation.找到最简单的解决方案
Easiest solution found
一个适用于许多 UITextField 的小修复:
A little fix that works for many UITextFields:
RPDP 的代码成功地将文本字段移出了键盘。 但是,当您在使用并关闭键盘后滚动到顶部时,顶部已向上滚动到视图之外。 对于模拟器和设备来说都是如此。 要阅读该视图顶部的内容,必须重新加载视图。
他的以下代码不是应该使视图恢复正常吗?
RPDP's code successfully moves the text field out of the way of the keyboard. But when you scroll to the top after using and dismissing the keyboard, the top has been scrolled up out of the view. This is true for the Simulator and the device. To read the content at the top of that view, one has to reload the view.
Isn't his following code supposed to bring the view back down?
要恢复到原始视图状态,请添加:
To bring back to original view state, add:
试试这个小技巧。
Try this short trick.
有很多解决方案,但我花了几个小时才开始工作。 所以,我把这段代码放在这里(只需粘贴到项目中,不需要任何修改):
PS:我希望代码可以帮助人们快速达到预期的效果。
(Xcode 4.5)
There so many solutions, but I've spend some hours before it start works. So, I put this code here (just paste to the project, any modifications needn't):
P.S: I hope the code help somebody make desired effect quickly.
(Xcode 4.5)
@user271753
要将您的视图恢复到原始添加:
@user271753
To get your view back to original add:
它不需要滚动视图就能够移动视图框架。 您可以更改
viewcontroller的
视图的框架,以便整个视图向上移动到足以将firstresponder文本字段放在键盘上方。 当我遇到这个问题时,我创建了一个 UIViewController 的子类来执行此操作。 它观察键盘将出现的通知并找到第一响应者子视图,并且(如果需要)它会将主视图向上动画化,以便第一响应者位于键盘上方。 当键盘隐藏时,它会将视图动画恢复到原来的位置。要使用此子类,请使您的自定义视图控制器成为 GMKeyboardVC 的子类并且它继承了这个功能(只要确定你是否实现了 viewWillAppear 和 viewWillDisappear ,它们就必须调用 super )。 该课程位于 github 上。
It doesn't require a scroll view to be able to move the view frame. You can change the frame of a
viewcontroller's
view so that the entire view moves up just enough to put the firstresponder text field above the keyboard. When I ran into this problem I created a subclass ofUIViewController
that does this. It observes for the keyboard will appear notification and finds the first responder subview and (if needed) it animates the main view upward just enough so that the first responder is above the keyboard. When the keyboard hides, it animates the view back where it was.To use this subclass make your custom view controller a subclass of GMKeyboardVC and it inherits this feature (just be sure if you implement
viewWillAppear
andviewWillDisappear
they must call super). The class is on github.斯威夫特4。
您可以使用
UIKeyBoard
和动画
轻松上下移动UITextField
或UIView
Swift 4 .
You Can Easily Move Up And Down
UITextField
OrUIView
WithUIKeyBoard
WithAnimation
这是我针对特定布局提出的黑客解决方案。 该解决方案与 Matt Gallagher 解决方案类似,即将一个部分滚动到视图中。 我对 iPhone 开发还是个新手,不熟悉布局的工作原理。 因此,这个黑客。
我的实现需要支持在单击字段时滚动,以及当用户在键盘上选择下一个时支持滚动。
我有一个高度为 775 的 UIView。控件基本上以 3 个为一组分布在一个很大的空间中。 我最终得到了以下 IB 布局。
这里有一个技巧,
我将 UIScrollView 高度设置为比实际布局 (1250) 大 500 个单位。 然后,我创建了一个包含需要滚动到的绝对位置的数组,以及一个根据 IB 标签编号获取它们的简单函数。
现在您需要做的就是在 textFieldDidBeginEditing 和 textFieldShouldReturn (如果您要创建下一个字段导航,则为后一行)中使用以下两行代码作为
示例。
此方法不像其他方法那样“向后滚动”。 这不是一个要求。 同样,这是一个相当“高”的 UIView,我没有时间学习内部布局引擎。
Here is the hack solution I came up with for a specific layout. This solution is similar to Matt Gallagher solution in that is scrolls a section into view. I am still new to iPhone development, and am not familiar with how the layouts work. Thus, this hack.
My implementation needed to support scrolling when clicking in a field, and also scrolling when the user selects next on the keyboard.
I had a UIView with a height of 775. The controls are spread out basically in groups of 3 over a large space. I ended up with the following IB layout.
Here comes the hack
I set the UIScrollView height to 500 units larger then the actual layout (1250). I then created an array with the absolute positions I need to scroll to, and a simple function to get them based on the IB Tag number.
Now all you need to do is use the following two lines of code in textFieldDidBeginEditing and textFieldShouldReturn (the latter one if you are creating a next field navigation)
An example.
This method does not 'scroll back' as other methods do. This was not a requirement. Again this was for a fairly 'tall' UIView, and I did not have days to learn the internal layout engines.
根据 文档,从 iOS 3.0 开始,当对文本字段进行内联编辑时,
UITableViewController
类会自动调整其表格视图的大小和位置。 我认为将文本字段放入UITableViewCell
中是不够的,正如一些人指出的那样。来自 文档:
As per the docs, as of iOS 3.0, the
UITableViewController
class automatically resizes and repositions its table view when there is in-line editing of text fields. I think it's not sufficient to put the text field inside aUITableViewCell
as some have indicated.From the docs:
您只需复制粘贴下面的示例代码并更改您的文本字段或任何您想要向上移动的视图。
第 1 步
步骤 2
第 3 步
参考:
好吧,请欣赏这个人,他分享了这个漂亮的代码片段、干净的解决方案。
希望这对那里的人有帮助。
You need to just copy-paste below sample code and change your textfield or any view which you want to move up.
Step-1
Step-2
Step-3
Reference:
well, Please appreciate this guy, who shared this beautiful code snip, clean solution.
Hope this would be surly helpful someone out there.
一直在为该主题的初学者寻找一个好的教程,找到了最好的教程 此处。
在教程底部的
MIScrollView.h
示例中,请确保在您看到的位置添加一个空格。
Been searching for a good tutorial for beginners on the subject, found the best tutorial here.
In the
MIScrollView.h
example at the bottom of the tutorial be sure to put a space atas you see.
当
UITextField
位于UITableViewCell
中时,应该自动设置滚动。如果不是,可能是因为表格视图的代码/设置不正确。
例如,当我重新加载底部有一个
UITextField
的长表时,如下所示,底部的文本字段被我在文本字段内单击时出现的键盘遮挡。
为了解决这个问题,我必须这样做 -
When
UITextField
is in aUITableViewCell
scrolling should be setup automatically.If it is not it is probably because of incorrect code/setup of the tableview.
For example when i reloaded my long table with one
UITextField
at the bottom as follows,then my textfield at the bottom was obscured by the keyboard which appeared when I clicked inside the textfield.
To fix this I had to do this -
使用这个第三方,你甚至不需要写一行
https://github.com/hackiftekhar/IQKeyboardManager< /a>
下载项目并将
IQKeyboardManager
拖放到您的项目中。如果您发现任何问题,请阅读
README
文档。伙计们,这确实消除了管理键盘的麻烦。
Use this third party you don't need to write even one line
https://github.com/hackiftekhar/IQKeyboardManager
download project and drag and drop
IQKeyboardManager
in your project.If you find any issue please read
README
document.Guys really its remove headache to manage keyboard.
注意:此答案假设您的文本字段位于滚动视图中。
我更喜欢使用scrollContentInset和scrollContentOffset来处理这个问题,而不是弄乱我的视图的框架。
首先让我们监听键盘通知
下一步是保留一个代表当前第一响应者的属性(当前拥有键盘的 UITextfield/ UITextVIew)。
我们使用委托方法来设置此属性。 如果您使用其他组件,则需要类似的组件。
请注意,对于文本字段,我们在 didBeginEditing 中设置它,对于 textView,我们在 shouldBeginEditing 中设置它。 这是因为由于某种原因,textViewDidBeginEditing 在 UIKeyboardWillShowNotification 之后被调用。
最后,这就是神奇之处
Note: this answer assumes your textField is in a scrollView.
I prefer to deal with this using scrollContentInset and scrollContentOffset instead of messing with the frames of my view.
First let's listen for the keyboard notifications
Next step is to keep a property that represents the current first responder (UITextfield/ UITextVIew that currently has the keyboard).
We use the delegate methods to set this property. If you're using another component, you will need something similar.
Note that for textfield we set it in didBeginEditing and for textView in shouldBeginEditing. This is because textViewDidBeginEditing gets called after UIKeyboardWillShowNotification for some reason.
Finally, here's the magic
这是使用 Swift 的解决方案。
This is the solution using Swift.
尝试这个:
Try this:
如果您现在的内容不适合 iPhone 屏幕,您只需要一个
ScrollView
。 (如果您添加ScrollView
作为组件的超级视图只是为了让TextField
在键盘出现时向上滚动,那么就不需要它。)标准防止
TextField
被键盘覆盖的方法是在显示键盘时向上/向下移动视图。这是一些示例代码:
You will only need a
ScrollView
if the contents you have now do not fit in the iPhone screen. (If you are adding theScrollView
as the superview of the components just to make theTextField
scroll up when keyboard comes up, then it's not needed.)The standard way to prevent the
TextField
s from being covered by the keyboard is to move the view up/down whenever the keyboard is shown.Here is some sample code:
我还遇到了很多由多个 UITextFields 组成的 UIScrollView 的问题,其中一个或多个在编辑时会被键盘遮挡。
如果您的
UIScrollView
无法正确滚动,请考虑以下事项。1) 确保您的 contentSize 大于
UIScrollView
框架大小。 理解 UIScrollViews 的方法是,UIScrollView 就像 contentSize 中定义的内容的查看窗口。 因此,为了让UIScrollview
滚动到任意位置,contentSize 必须大于UIScrollView
。 否则,不需要滚动,因为 contentSize 中定义的所有内容都已经可见。 顺便说一句,默认 contentSize =CGSizeZero
。2) 现在您已经了解
UIScrollView
实际上是进入“内容”的窗口,确保键盘不会遮挡UIScrollView
查看“窗口”的方法是调整UIScrollView
的大小,以便当键盘存在时,您可以将UIScrollView
窗口的大小调整为原始UIScrollView
frame.size.height减去键盘的高度。 这将确保您的窗口只有那么小的可视区域。3)这里有一个问题:当我第一次实现这个时,我想我必须获取编辑后的文本字段的CGRect并调用UIScrollView的scrollRecToVisible方法。 我通过调用
scrollRecToVisible
方法实现了UITextFieldDelegate
方法textFieldDidBeginEditing
。 这实际上产生了一个奇怪的副作用,即滚动会将UITextField
固定到位。 在很长一段时间里我都不明白那是什么。 然后我注释掉了textFieldDidBeginEditing
Delegate 方法,一切都正常了!!(???)。 事实证明,我相信 UIScrollView 实际上隐式地将当前编辑的 UITextField 隐式带入可视窗口。 我对UITextFieldDelegate
方法的实现以及对scrollRecToVisible
的后续调用是多余的,并且是导致奇怪副作用的原因。因此,以下是在键盘出现时将
UIScrollView
中的UITextField
正确滚动到位的步骤。viewDidLoad
注册键盘通知viewDidUnload
取消注册键盘通知contentSize
并大于您的UIScrollView< /code> 在
viewDidLoad
处UIScrollView
UIScrollView code> 当键盘消失时。UITextField
时都会发送键盘通知,即使键盘已存在以避免缩小UIScrollView
当它已经收缩时需要注意的是,即使当您按 Tab 键时键盘已经在屏幕上,
UIKeyboardWillShowNotification
也会触发另一个UITextField
。 我通过使用 ivar 来解决这个问题,以避免在键盘已经在屏幕上时调整UIScrollView
的大小。 当键盘已经存在时,无意中调整UIScrollView
的大小将是灾难性的!希望这段代码可以为你们中的一些人省去很多麻烦。
I was also having a lot of issue with a
UIScrollView
composing of multipleUITextFields
, of which, one or more of them would get obscured by the keyboard when they are being edited.Here are some things to consider if your
UIScrollView
is not properly scrolling.1) Ensure that your contentSize is greater than the
UIScrollView
frame size. The way to understandUIScrollViews
is that theUIScrollView
is like a viewing window on the content defined in the contentSize. So when in order for theUIScrollview
to scroll anywhere, the contentSize must be greater than theUIScrollView
. Else, there is no scrolling required as everything defined in the contentSize is already visible. BTW, default contentSize =CGSizeZero
.2) Now that you understand that the
UIScrollView
is really a window into your "content", the way to ensure that the keyboard is not obscuring yourUIScrollView's
viewing "window" would be to resize theUIScrollView
so that when the keyboard is present, you have theUIScrollView
window sized to just the originalUIScrollView
frame.size.height minus the height of the keyboard. This will ensure that your window is only that small viewable area.3) Here's the catch: When I first implemented this I figured I would have to get the
CGRect
of the edited textfield and callUIScrollView's
scrollRecToVisible method. I implemented theUITextFieldDelegate
methodtextFieldDidBeginEditing
with the call to thescrollRecToVisible
method. This actually worked with a strange side effect that the scrolling would snap theUITextField
into position. For the longest time I couldn't figure out what it was. Then I commented out thetextFieldDidBeginEditing
Delegate method and it all work!!(???). As it turned out, I believe theUIScrollView
actually implicitly brings the currently editedUITextField
into the viewable window implicitly. My implementation of theUITextFieldDelegate
method and subsequent call to thescrollRecToVisible
was redundant and was the cause of the strange side effect.So here are the steps to properly scroll your
UITextField
in aUIScrollView
into place when the keyboard appears.viewDidLoad
viewDidUnload
contentSize
is set and greater than yourUIScrollView
atviewDidLoad
UIScrollView
when the keyboard is presentUIScrollView
when the keyboard goes away.UITextField
is tabbed even if the keyboard is already present to avoid shrinking theUIScrollView
when it's already shrunkOne thing to note is that the
UIKeyboardWillShowNotification
will fire even when the keyboard is already on the screen when you tab on anotherUITextField
. I took care of this by using an ivar to avoid resizing theUIScrollView
when the keyboard is already on the screen. Inadvertently resizing theUIScrollView
when the keyboard is already there would be disastrous!Hope this code saves some of you a lot of headache.
实际上最好只使用 Apple 的实现,如 文档。 然而,他们提供的代码是错误的。 将注释下方的
keyboardWasShown:
中找到的部分替换为以下内容:Apple 代码的问题如下:
(1) 他们总是计算该点是否在视图的框架内,但它是一个 ScrollView,因此它可能已经滚动,您需要考虑该偏移量:
(2) 他们将 contentOffset 移动键盘的高度,但我们想要相反的高度(我们希望将
contentOffset
移动屏幕上可见的高度,而不是屏幕上不可见的高度):It's actually best just to use Apple's implementation, as provided in the docs. However, the code they provide is faulty. Replace the portion found in
keyboardWasShown:
just below the comments to the following:The problems with Apple's code are these:
(1) They always calculate if the point is within the view's frame, but it's a
ScrollView
, so it may already have scrolled and you need to account for that offset:(2) They shift the contentOffset by the height of the keyboard, but we want the opposite (we want to shift the
contentOffset
by the height that is visible on the screen, not what isn't):在
textFieldDidBeginEditting
和textFieldDidEndEditing
中调用函数[self animateTextField:textField up:YES]
如下:我希望这段代码会对您有所帮助。
雨燕5
In
textFieldDidBeginEditting
and intextFieldDidEndEditing
call the function[self animateTextField:textField up:YES]
like so:I hope this code will help you.
Swift 5
仅使用 TextFields:
1a) 使用
Interface Builder
:选择所有 TextFields => 编辑 => 嵌入 => ScrollView1b) 在 UIScrollView 中手动嵌入 TextFields(称为scrollView)
2) 设置 UITextFieldDelegate
3) 设置每个
textField.delegate = self;
(或在 Interface Builder 中建立连接代码>)4) 复制/粘贴:
Just using TextFields:
1a) Using
Interface Builder
: Select All TextFields => Edit => Embed In => ScrollView1b) Manually embed TextFields in UIScrollView called scrollView
2) Set
UITextFieldDelegate
3) Set each
textField.delegate = self;
(or make connections inInterface Builder
)4) Copy / Paste:
对于通用解决方案,这是我实现IQKeyboardManager的方法。
Step1:- 我添加了
UITextField
、UITextView
和UIKeyboard
在单例类中。 我称之为 IQKeyboardManager。Step2:- 如果找到
UIKeyboardWillShowNotification
、UITextFieldTextDidBeginEditingNotification
或UITextViewTextDidBeginEditingNotification
通知,我会尝试获取topMostViewControllerUIWindow.rootViewController
层次结构中的 code> 实例。 为了正确地显示UITextField
/UITextView
,需要调整topMostViewController.view
的框架。第3步:-我计算了
topMostViewController.view
相对于第一个响应的UITextField
/UITextView
的预期移动距离。第四步:-我根据预期的移动距离向上/向下移动
topMostViewController.view.frame
。Step5:- 如果发现
UIKeyboardWillHideNotification
、UITextFieldTextDidEndEditingNotification
或UITextViewTextDidEndEditingNotification
通知,我会再次尝试获取topMostViewController<
UIWindow.rootViewController
层次结构中的 /code> 实例。Step6:- 我计算了
topMostViewController.view
的受干扰距离,需要将其恢复到原始位置。Step7:-我根据被干扰的距离将
topMostViewController.view.frame
恢复下来。Step8:- 我在应用程序加载时实例化了单例 IQKeyboardManager 类实例,因此每个
UITextField/
UITextView
会根据预期的移动距离自动调整。这就是 IQKeyboardManager 为您所做的一切,无需任何代码! 只需要将相关源文件拖放到项目中即可。 IQKeyboardManager 还支持设备方向、自动 UIToolbar 管理、KeybkeyboardDistanceFromTextField 比你想象的要多得多。
For Universal Solution, Here was my approach for implementing IQKeyboardManager.
Step1:- I Added global notifications of
UITextField
,UITextView
, andUIKeyboard
in a singleton class. I call it IQKeyboardManager.Step2:- If found
UIKeyboardWillShowNotification
,UITextFieldTextDidBeginEditingNotification
orUITextViewTextDidBeginEditingNotification
notifications, I try to gettopMostViewController
instance from theUIWindow.rootViewController
hierarchy. In order to properly uncoverUITextField
/UITextView
on it,topMostViewController.view
's frame needs to be adjusted.Step3:- I calculated expected move distance of
topMostViewController.view
with respect to first respondedUITextField
/UITextView
.Step4:- I moved
topMostViewController.view.frame
up/down according to the expected move distance.Step5:- If found
UIKeyboardWillHideNotification
,UITextFieldTextDidEndEditingNotification
orUITextViewTextDidEndEditingNotification
notification, I again try to gettopMostViewController
instance from theUIWindow.rootViewController
hierarchy.Step6:- I calculated disturbed distance of
topMostViewController.view
which needs to be restored to it's original position.Step7:- I restored
topMostViewController.view.frame
down according to the disturbed distance.Step8:- I instantiated singleton IQKeyboardManager class instance on app load, so every
UITextField
/UITextView
in the app will adjust automatically according to the expected move distance.That's all IQKeyboardManager do for you with NO LINE OF CODE really!! only need to drag and drop related source file to project. IQKeyboardManager also support Device Orientation, Automatic UIToolbar Management, KeybkeyboardDistanceFromTextField and much more than you think.
我已经组合了一个通用的嵌入式
UIScrollView
、UITableView
甚至UICollectionView
子类,负责将其中的所有文本字段移出键盘的方式。当键盘即将出现时,子类将找到即将编辑的子视图,并调整其框架和内容偏移量以确保该视图可见,并带有与键盘弹出窗口相匹配的动画。 当键盘消失时,它会恢复原来的大小。
它基本上应该适用于任何设置,无论是基于
UITableView
的界面,还是由手动放置的视图组成的界面。这是:将文本字段移出键盘的解决方案
I've put together a universal, drop-in
UIScrollView
,UITableView
and evenUICollectionView
subclass that takes care of moving all text fields within it out of the way of the keyboard.When the keyboard is about to appear, the subclass will find the subview that's about to be edited, and adjust its frame and content offset to make sure that view is visible, with an animation to match the keyboard pop-up. When the keyboard disappears, it restores its prior size.
It should work with basically any setup, either a
UITableView
-based interface, or one consisting of views placed manually.Here' tis: solution for moving text fields out of the way of the keyboard
这将为您完成所有操作,只需将它们放入您的视图控制器类中,并为您的视图控制器实现
UITextFieldDelegate
即可。 将 textField 的委托设置为self
实现委托回调方法:
对于 Swift 4、4.2、5:
更改
为
有关此实现的最后一个注释:如果在显示键盘时将另一个视图控制器推入堆栈,则会产生错误,视图返回到其中心框架,但键盘偏移量不会重置。 例如,您的键盘是 nameField 的第一响应者,但随后您按下一个按钮,将帮助视图控制器推送到堆栈上。 要修复偏移错误,请确保在离开视图控制器之前调用 nameField.resignFirstResponder(),并确保同时调用 textFieldDidEndEditing 委托方法。 我在 viewWillDisappear 方法中执行此操作。
This will do everything for you, just put these in your view controller class and implement the
UITextFieldDelegate
to your view controller & set the textField's delegate toself
Implement the delegate callback methods:
For Swift 4, 4.2, 5:
Change
to
Last note about this implementation: If you push another view controller onto the stack while the keyboard is shown, this will create an error where the view is returned back to its center frame but keyboard offset is not reset. For example, your keyboard is the first responder for nameField, but then you push a button that pushes your Help View Controller onto your stack. To fix the offset error, make sure to call nameField.resignFirstResponder() before leaving the view controller, ensuring that the textFieldDidEndEditing delegate method is called as well. I do this in the viewWillDisappear method.
已经有很多答案,但上述解决方案仍然没有一个具有“完美”无错误、向后兼容和无闪烁动画所需的所有精美定位内容。 (一起动画框架/边界和 contentOffset 时的错误、不同的界面方向、iPad 分体式键盘……)
让我分享我的解决方案:
(假设您已设置
UIKeyboardWill(Show|Hide)Notification
)There are already a lot of answers, but still none of the solutions above had all the fancy positioning stuff required for a "perfect" bug-free, backwards compatible and flicker-free animation. (bug when animating frame/bounds and contentOffset together, different interface orientations, iPad split keyboard, ...)
Let me share my solution:
(assuming you have set up
UIKeyboardWill(Show|Hide)Notification
)Shiun 说,“事实证明,我相信 UIScrollView 实际上隐式地将当前编辑的 UITextField 隐式地带入可视窗口” 这对于 iOS 3.1.3 似乎是正确的,但对于 3.2、4.0 或 4.1 则不然。 我必须添加显式的scrollRectToVisible 才能使UITextField 在iOS >= 3.2 上可见。
Shiun said "As it turned out, I believe the UIScrollView actually implicitly brings the currently edited UITextField into the viewable window implicitly" This seems to be true for iOS 3.1.3, but not 3.2, 4.0, or 4.1. I had to add an explicit scrollRectToVisible in order to make the UITextField visible on iOS >= 3.2.