Move textfield when keyboard appears swift
Solution 1
There are a couple of improvements to be made on the existing answers.
Firstly the UIKeyboardWillChangeFrameNotification is probably the best notification as it handles changes that aren't just show/hide but changes due to keyboard changes (language, using 3rd party keyboards etc.) and rotations too (but note comment below indicating the keyboard will hide should also be handled to support hardware keyboard connection).
Secondly the animation parameters can be pulled from the notification to ensure that animations are properly together.
There are probably options to clean up this code a bit more especially if you are comfortable with force unwrapping the dictionary code.
class MyViewController: UIViewController {
// This constraint ties an element at zero points from the bottom layout guide
@IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(self.keyboardNotification(notification:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func keyboardNotification(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let endFrameY = endFrame?.origin.y ?? 0
let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if endFrameY >= UIScreen.main.bounds.size.height {
self.keyboardHeightLayoutConstraint?.constant = 0.0
} else {
self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0
}
UIView.animate(
withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
Solution 2
If you're using Auto Layout, I assume you've set the Bottom Space to Superview constraint. If that's the case, you simply have to update the constraint's value. Here's how you do it with a little bit of animation.
func keyboardWasShown(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.bottomConstraint.constant = keyboardFrame.size.height + 20
})
}
The hardcoded 20 is added only to pop the textfield above the keyboard just a bit. Otherwise the keyboard's top margin and textfield's bottom margin would be touching.
When the keyboard is dismissed, reset the constraint's value to its original one.
Solution 3
A simple solution is to move view up with constant of keyboard height.
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}
@objc func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y = -150 // Move view 150 points upward
}
@objc func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y = 0 // Move view to original position
}
Swift 5:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(sender:)), name: UIResponder.keyboardWillShowNotification, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil);
Solution 4
For moving your view while editing textfield try this , I have applied this ,
Option 1 :- ** **Update in Swift 5.0 and iPhone X , XR , XS and XS Max Move using NotificationCenter
Register this Notification in
func viewWillAppear(_ animated: Bool)
Deregister this Notification in
func viewWillDisappear(_ animated: Bool)
Note:- If you will not deregister than it will call from child class and will reason of crashing or else.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil )
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow( notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
var newHeight: CGFloat
let duration:TimeInterval = (notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if #available(iOS 11.0, *) {
newHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
newHeight = keyboardFrame.cgRectValue.height
}
let keyboardHeight = newHeight + 10 // **10 is bottom margin of View** and **this newHeight will be keyboard height**
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: {
self.view.textViewBottomConstraint.constant = keyboardHeight **//Here you can manage your view constraints for animated show**
self.view.layoutIfNeeded() },
completion: nil)
}
}
Option 2 :- Its work fine
func textFieldDidBeginEditing(textField: UITextField) {
self.animateViewMoving(up: true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
self.animateViewMoving(up: false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
var movementDuration:NSTimeInterval = 0.3
var movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
I got this answer from this source UITextField move up when keyboard appears in Swift
IN the Swift 4 ---
func textFieldDidBeginEditing(_ textField: UITextField) {
animateViewMoving(up: true, moveValue: 100)
}
func textFieldDidEndEditing(_ textField: UITextField) {
animateViewMoving(up: false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:TimeInterval = 0.3
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
Solution 5
I love clean Swift code. So here's the tightest code I could come up with to move a text view up/down with the keyboard. It's currently working in an iOS8/9 Swift 2 production app.
UPDATE (March 2016): I just tightened up my previous code as much as possible. Also, there are a bunch of popular answers here that hardcode the keyboard height and animation parameters. There's no need for that, not to mention that the numbers in these answers don't always line up with the actual values I'm seeing on my 6s+ iOS9 (keyboard height of 226, duration of 0.25, and animation curve of 7). In any case, it's almost no extra code to get those values straight from the system. See below.
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateWithKeyboard:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateWithKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
}
func animateWithKeyboard(notification: NSNotification) {
// Based on both Apple's docs and personal experience,
// I assume userInfo and its documented keys are available.
// If you'd like, you can remove the forced unwrapping and add your own default values.
let userInfo = notification.userInfo!
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let moveUp = (notification.name == UIKeyboardWillShowNotification)
// baseContraint is your Auto Layout constraint that pins the
// text view to the bottom of the superview.
baseConstraint.constant = moveUp ? -keyboardHeight : 0
let options = UIViewAnimationOptions(rawValue: curve << 16)
UIView.animateWithDuration(duration, delay: 0, options: options,
animations: {
self.view.layoutIfNeeded()
},
completion: nil
)
}
NOTE: This code covers the most comment/general case. However, more code may be needed to handle different orientations and/or custom keyboards Here's an in-depth article on working with the iOS keyboard. If you need to handle every scenario, this may help.
Related videos on Youtube
Pedro Manfredi
Updated on July 08, 2022Comments
-
Pedro Manfredi almost 2 years
I'm using Swift for programing with iOS and I'm using this code to move the
UITextField
, but it does not work. I call the functionkeyboardWillShow
correctly, but the textfield doesn't move. I'm using autolayout.override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } deinit { NSNotificationCenter.defaultCenter().removeObserver(self); } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { //let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) var frame = self.ChatField.frame frame.origin.y = frame.origin.y - keyboardSize.height + 167 self.chatField.frame = frame println("asdasd") } }
-
Dan Beaulieu over 8 yearsWalkthrough guide with Project files: codebeaulieu.com/43/…
-
Ricardo over 7 yearsPerhaps deinit and viewDidLoad are not balanced.
-
Codetard almost 7 yearsBased on both Apple's docs and personal experience. Here's my git repo using UIScrollView to move TF: github.com/29satnam/MoveTextFieldWhenKeyboardAppearsSwift
-
-
Pedro Manfredi almost 10 yearsCan you explain me pls how i define it? Thanks! i always control all on storyboard
-
Isuru almost 10 yearsSelect the textfield, go to Editor -> pin and then you'll see some constraint options.
-
Pedro Manfredi almost 10 yearsyep i have it but when i use self.bottomConstraint.constant = keyboardFrame.size.height + 20 i don't have a member named bottomConstraint. Thanks!!
-
Isuru almost 10 yearsbottomConstraint is the name I gave to the constraint. I selected the constrant, dragged and created an IBOutlet to it and gave that name. You can create IBOutlets to constraints just as you could do with other UI elements like buttons and text fields.
-
Haring10 over 9 yearsWhat can I do if I am not using Auto Layout?
-
Isuru over 9 years@JoshHarington Have you looked into a library like this one?
-
ndbroadbent over 9 yearsHi @joseph-lord, I think the
animateWithDuration
is actually doing nothing. Try changing the duration to something like10.0
seconds, or even just commenting out the whole animation call, and just runningself.view.layoutIfNeeded()
instead. For me, it seems to be overridden by the keyboard's own animation. Maybe iOS callscommitAnimation
after calling the keyboard notification. -
Joseph Lord over 9 years@nathan.f77 Are you changing a
keyboardHeightLayoutConstraint
that has been set up between the bottom thing that you want to animate and the bottom layout guide? That line is key and the constraint should not benil
. Theself.view.layoutIfNeeded
in the animation block should apply the updated constraint. -
Ken Roy over 9 yearsI like this simple solution. But I added a keyboardShowing boolean since I have move than one textfield. I only move the keyboard once while it is showing. Thanks.
-
Adam Johns over 9 yearsThis answer worked great except the animation happened immediately for me. Check How do I animate constraint changes? for how to animate properly.
-
ericgu over 9 yearsinstead of moving the view, move the textView
-
Hlung about 9 years@JosephLord nice. but I found this doesn't work when keyboard is hiding because
endFrame?.size.height
is not nil. I got the end frame asUIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 1024}, {768, 264}}";
. Ran on iOS 8.3 iPad Simulator, Portrait. Xcode6.3 beta4. -
Joseph Lord about 9 years@Hlung If that is the endframe on hiding it sounds like the keyboard animated offscreen but didn't actually shrink. You may need to get the window size to know for sure that 1024 is the bottom of the screen. It would then need the constraint constant set to screenheight - endFrame.origin.y.
-
Jeffrey Neo about 9 yearsThis will keep minus the view's y value if user switch the input language.
-
Sashi about 9 yearsinstead of changing the self.view i did self.myConstraint value, it works but the thing is the view (to which constraint is applied) keeps on moving up. did anyone face this issue ?
-
Saqib Omer about 9 yearsYou are adding constraint constant which will affect the view to which that constraint is attached. @Sashi
-
Sashi about 9 yearsYea, I figured that out after a while. I was adding some specified number of pixels every time keyboard is clicked, but forgot to remove that while hiding keyboard. Now the view moves correctly, but is there a way to make that transition smooth? Like animating it up by that pixels?
-
Sashi about 9 yearsInside keyboardWillShow method check for the condition if self.centerYConstraint.constant == self.originalCenterYConstraint then have that one line of code in between this condition. OriginalCenterYContraint is the original value of centerYContraint that I'm storing in viewdidload. This worked for me.
-
Saqib Omer about 9 yearsThere are no pixels in iOS instead there are points. For animation see this question. stackoverflow.com/questions/25693130/… or better ask new question.
-
Joseph Lord about 9 yearsSeems to be Swift 1.1 and I think won't compile in Swift 1.2 because it uses
as
for force casts.as!
may work but as you can see elsewhere on this page I avoid force casts and force unwrapping myself. -
Gabriel Goncalves about 9 yearsif the keyboard doesn't hide, try using this code if endFrame?.origin.y >= UIScreen.mainScreen().bounds.size.height { self.keyboardHeightLayoutConstraint?.constant = 0.0 } else { self.keyboardHeightLayoutConstraint?.constant = endFrame.size.height }
-
superarts.org about 9 yearsYou need to create an
IBOutlet
for the constraint:@IBOutlet var constraint_input: NSLayoutConstraint!
-
vinbhai4u about 9 years@Isuru Do I have to set some thing else, because when I gave the above function its not even getting into that function, should I register some notification? Please help
-
Isuru about 9 years@vinbhai4u You have to register for
UIKeyboardWillShowNotification
notification. Look at the code in the OP's question. -
vinbhai4u about 9 years@Isuru I am trying to achieve stackoverflow.com/questions/30533285/scrollview-with-tab-bar can you please take a look at the question I have asked? it would be a great help
-
vinbhai4u about 9 yearsThanks @Isuru I got the answer and posted in stackoverflow.com/questions/30533285/scrollview-with-tab-bar thanks for your help
-
nsij22 about 9 yearsWhen the keyboard is dismissed it does not seem to reset the view. This is probably just an overall error with my constraints but yeah :S
-
Rhuantavan about 9 yearsThis solution worked for me, although I had to do some additional work: declare an
var animateDistance: CGFloat!
plus I had to handle the UIKeyboardWillHideNotification for when the user presses the hide keyboard button. -
KML almost 9 yearsI like this simple solution, but ti does not work for me. I can see the view being moved, but then it resets back to it's original place/frame. It is as if ViewDidLayoutSubviews are interfering..
-
KML almost 9 yearsOr maybe it has something to do with AutoLayout?
-
Saqib Omer almost 9 yearsIt is not changing any layout constraint. Add a breakpoint in keyboardWillHide function to check when it is being called.
-
Joseph Lord almost 9 yearskeyBoardHeightLayoutConstraint is a constraint defined in InterfaceBuilder constraining the bottom of the view that you want to move/shrink to the bottom layout guide or the bottom of the main view for the viewcontroller. The constant is initially set to zero and will be adjusted to make room for the keyboard when the keyboard appears or changes size.
-
Max almost 9 years@AdamJohns To animate the constraint change, update the constant outside the
animateWithDuration
and callself.view.layoutIfNeeded()
inside the animate block. -
Ashok almost 9 yearsNice answer, Thanks. It's always better to update constraint instead of frame, and it's simple.
-
kye over 8 years@Sashi could you post your solution please? currently facing the same issue
-
onCompletion over 8 yearsThe code is nice..but the problem is when you tap on different textfields in a single viewcontroller repeatedly then it actually moving the complete view continuously and throughing the textfields out of the screen...
-
Thiha Aung over 8 years@Jogendra.Com,Thanks for your hard work.But,It work best on iPhone 5,4s and 6.But,how can i disable it on iPhone 6plus and iPad (higher ones)
-
Eduard Feicho over 8 yearsWorks best for me so far. I suggest to read out the constraint's initial constant in case it's not zero: var keyboardHeightLayoutConstraintConstant: CGFloat? = 0 ... override func viewDidAppear(animated: Bool) { self.keyboardHeightLayoutConstraintConstant = self.keyboardHeightLayoutConstraint?.constant } ... func keyboardNotification(notification: NSNotification) { .... self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0 self.keyboardHeightLayoutConstraint?.constant += keyboardHeightLayoutConstraintConstant!
-
Eduard Feicho over 8 yearsI didn't read the "PLEASE NOTE" at the bottom and just realised that @Gabox solved my issue that the keyboard was simply translated rather than shrunk!! Thanks.
-
David Alejandro Londoño Mejía over 8 yearsthe constrain dont go to zero after keyboard dismissed
-
Hobbyist over 8 years
bottomConstraint
is not valid -
user1354603 over 8 yearsThis worked for me, I created a top constraint with priority 999 and a bottom constraint with constant >= 0. So when keyboard pushes layout up the top constraint will allow it as it has lower priority
-
enlyte over 8 yearsWhat if you have a tableView above the view you are trying to move? I got the code to work in a separate view, with no constraints (Table views) above it, but how would you handle the above constraint?
-
scootermg over 8 yearsCompiles now in Swift 1.2. And I added a comment to the code re: the forced unwrapping. Cheers.
-
scootermg over 8 yearsOops. I meant Swift 2.
-
gunwin over 8 yearsInstead of using
self.view.frame.origin.y -= 150
useself.view.frame.origin.y = -150
and instead ofself.view.frame.origin.y += 150
useself.view.frame.origin.y = 0
. This prevents the view moving 150 each time a new field is touched. -
limfinity about 8 yearsDepending on how you linked up your
baseConstraint
it might bebaseConstraint.constant = moveUp ? keyboardHeight : 0
instead ofbaseConstraint.constant = moveUp ? -keyboardHeight : 0
. -
Tib almost 8 yearsmuch more "Swift" than the other solutions / works great / reusable in every controller without rewriting everything -> definitely the best one here :)
-
Fonix almost 8 yearsfor some reason the view will animate with the keyboard when its dismissed, but the animation is skipped when it appears... even thought its the same code handling both, quite strange. if i use the UIKeyboardDidChangeFrameNotification it works fine though, but then the animation is delayed because the keyboard has to finish its animation first
-
Fonix almost 8 yearsok nevermind, it was just the simulator being silly, it works fine on device
-
Sachin Kumaram almost 8 yearsIt showing black screen after
UIKeyboardWillShowNotification
called. -
Kamalkumar.E almost 8 yearsUse above code to move the textfield above the keyboard in swift 2.2 it will work’s fine . i hope it will help some one.
-
Zaphod almost 8 yearsThat works like a charm... Thanks alot! But There's a slight problem on iPad when the keyboard is split or detached... Any good practice to handle these two special cases?
-
Thomas almost 8 years@Fonix I'm getting the issue you're talking about with the keyboard not animating on appearance, yet still working on disappearance with iOS 10 now. It was working fine before I updated to iOS 10 too. Is it still working fine on your device with the new upgrade?
-
GKK over 7 yearsI concur with @Max. To properly animate it you should update the constraint before calling the animateWithDuration method and then inside this method just call layoutIfNeeded over the self.view
-
Stephy Samaniego over 7 yearsHi, this works perfectly! it was the answer i was looking for, but when i tab outside for keyboard to dissapear, the view moves lower. what can i do?
-
schw4ndi over 7 yearsCould you please explain your edit? I couldn't get it to work. I have a UIScrollView with a Button at the bottom. I setted the class at the margin bottom constraint on the bottom.
-
Hlung over 7 years@schw4ndi to what views does your bottom constraints tied to? it should be connecting bottom of scrollview to the bottom of that scrollview's superview.
-
schw4ndi over 7 yearsOh thanks, i had the constraint between the button and the scrollView
-
jamesk over 7 yearsNote that
.UIKeyboardWillChangeFrame
doesn't fire when a hardware keyboard is connected, even though the iOS keyboard disappears. You need to observe.UIKeyboardWillHide
as well to catch that edge case. -
Joseph Lord over 7 years@jamesk Good catch, do you have a proposed edit? Is it as simple as adding the extra observer or does the handling code need updating too? I've not got time to experiment at the moment.
-
Pavlos over 7 years@Sulthan works okay.. My issue is that is getting a bit higher than the keybaord. is there any way we can fix this?
-
Valtoni Boaventura almost 7 yearsIt's worked if you put "Relation = Equal" too, without warnings.
-
Frederic Adda almost 7 yearsIf you put an equal relationship, it may work only in specific situations. In others you may have an auto layout inconsistency warning. It depends on your own layout. That's why I said "you may have to".
-
Valtoni Boaventura almost 7 yearsOk Frédéric, agreeded. Was a nice solution!
-
Mirko over 6 yearsmissing
import UIKit
-
Mythlandia over 6 yearsGreat solution! But you need the Safe Area.Bottom as the first item on the constraint (didn't work for me when it was the second item). And it worked best with the constant set to 0 as it preserves the constant and adjusts it, rather than just moving it far enough to show the field and keyboard.
-
JavaBeast about 6 yearsCode didnt work for me so i just removed if/else and replaced with
self.<enterbuttonname>.frame.origin.y = endFrameY - self.<enterbuttonname>.frame.height
-
Micro about 6 yearsneeds to be
UIKeyboardFrameEndUserInfoKey
-
Fraser about 6 yearsThere are several CocoaPods that provide robust keyboard avoiding solutions. I recommend github.com/IdleHandsApps/IHKeyboardAvoiding, but of course I do, I wrote it :)
-
giovannipds almost 6 years@Fraser I just couldn't get your CocoaPods working, how to import your module? Please improve the installation part of README.
-
Fraser almost 6 years@giovannipds
import IHKeyboardAvoiding
is all you need. Raise an issue on Github if you're still having issues -
giovannipds almost 6 years@Fraser thanks for answering, pretty sure I've tried that. It was probably an Xcode delay or something. Anyway, I dealt with it in other way.
-
jeet.chanchawat over 5 yearsDo you have KeyboardLayoutConstraint swift4 version ?
-
erdemgc over 5 yearsI tried but no chance, is UIScrollView needed or what?
-
ale_stro over 5 years@erdemgc did you see Example of usage? All you need is just UIViewControlller + addKeyboardChangeFrameObserver and then do not forget to remove it
-
smj over 5 years
NSNotification.Name.UIKeyboardWillShow
is Renamed toUIResponder.keyboardWillShowNotification
alsoUIKeyboardFrameBeginUserInfoKey
toUIResponder.keyboardFrameBeginUserInfoKey
-
MikeG over 5 yearsdoesn't work for Swift 4 you should edit the answer or don't mark it as a solution for Swift 4.x
-
a.masri about 5 years@JosephLord can you explain to me, why not used input accessory view ??
-
Joseph Lord about 5 years@a.masri The intention here is rearranging content on the screen to allow space for the keyboard. I believe the accessory view is for attaching additional keyboard specific functionality to the keyboard.
-
Huy-Anh Hoang about 5 yearsThe
removeKeyboardObserver()
method here does not actually remove the observer. If you don't call this, you will see aInvalid conditions for UIKeyboardWillChangeFrameNotification
in the console from the add method. If you call this, you will see the same error, meaning the observer isn't removed. The documentation states "To unregister observations, you pass the object returned by this method toremoveObserver(_:)
." So what you do instead is save the object returned by that method, then pass it in when you want to remove the observer. -
James Kim about 5 yearsActually, once scrollview is loaded, bound is assigned a value and you can't detect if a keyboard will be hidden if keyboard frame intersects with bound.
-
Hammad Tariq almost 5 yearsIf you are using Option 1, please be sure to add a constraint IBOutlet. You will create a constraint that you want to resize using Auto-layout then drag and drop it to the viewcontroller to create an IBOutlet that I reference it as self.iboutletConstraint.constant in the animate function. Also this does not re-adjust the outlet on hiding the keyboard, I handled that by resetting the constraint to it's original value.
-
Hide in bubble over 4 yearsDoes it work for TextView and how can I change title for return key "Done" ?
-
Raghib Arshi over 4 yearsGoto:- "IQKeyboardManager.m" Replace this line(Line No. 968):- [textField addDoneOnKeyboardWithTarget:self action:@selector(doneAction:) shouldShowPlaceholder:_shouldShowTextFieldPlaceholder] with this:- [textField addRightButtonOnKeyboardWithText:@"YOURTEXT" target:self action:@selector(doneAction:) shouldShowPlaceholder:_shouldShowTextFieldPlaceholder]; And haven't tried yet for the textview, hope this would help you.
-
ale_stro over 4 years@Hemang you can update any constraint you need. this closures shows you height of keyboard
-
Shahriyar over 4 yearsYou can use my gist it's well commented, it's made for views with ScrollView, but you can just change the scrollView part to your UIView it works perfectly. gist.github.com/Sjahriyar/916e93153a29dc602b45f29d39182352
-
Youstanzr over 4 yearsFor some reason, I was having an issue in keyboardWillShow function, the keyboardSize was getting wrong size after the first keyboard toggle (the first toggle has correct frame). I fixed this by changing it to guard let userInfo = notification.userInfo else {return} guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {return} let keyboardFrame = keyboardSize.cgRectValue if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= getMoveableDistance(keyboarHeight: keyboardFrame.height) } .Hope this will help if someone got the same issue :)
-
Raymond about 4 yearsI've been struggling for days to fix the animation issue with text view. For me UIKeyboardWillChangeFrame fixed the issue. It works perfectly with this notification instead of keyboardDidShowNotification or keyboardWillShowNotification notifications. Please mark UIKeyboardWillChangeFrame in bold to highlight it.
-
Muhammad Haroon Iqbal almost 4 yearsIt is working fine. but animation is missing. Thanks
-
Fahim Rahman over 3 yearsWorks like a charm
-
Parth Tamane over 3 yearsHow would I do this for a UI Created programmatically? Do I just define a let
bottomConstraint
in the viewController and then add it inNSLayoutConstraint.activate[]
? -
Parth Tamane over 3 yearsgot it to work will make a new answer. But there was a correction in the constraint setting.
self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0
this should beself.discussionsMessageBoxBottomAnchor.constant = -1 * (endFrame?.size.height ?? 0.0)
-
Joseph Lord over 3 years@ParthTamane I think it depends which way round the constraint is made. The original answer was written before iOS had anchors (or is that just the name you gave a constraint).
-
Parth Tamane over 3 yearsThe anchor is a NSLayoutConstraint. But the constraint is based on anchor: view.bottomAnchor
-
Anurag Soni about 3 yearsif you got nothing, then use this solution. perfect one to rescue you.
-
Gleny Rebellow over 2 yearsworking perfectly