Created
January 31, 2018 17:01
-
-
Save mlcollard/d7af589106103b4a4e426b6f7bd3bdba to your computer and use it in GitHub Desktop.
iOS: Active view controller with a closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Moving keyboard for item | |
// | |
// Note: Comments with this label are to explain semantics of iOS | |
// Do not use comments like these in your projects | |
import UIKit | |
class ViewController: UIViewController, UITextFieldDelegate { | |
// email address entry | |
// Note: Must create text field in storyboard, and connect to this IBOutlet | |
@IBOutlet weak var emailText: UITextField! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
self.emailText.delegate = self | |
// shifts the view up for space for the keyboard | |
NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil) { | |
notification in | |
// find the size of the keyboard | |
guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { | |
print("Error: Unable to get keyboard size") | |
return | |
} | |
// find the active view | |
guard let activeView = self.view.subviews.first(where: { $0.isFirstResponder }) else { | |
print("Error: no view is active") | |
return | |
} | |
// move the whole thing up if necessary | |
if keyboardSize.contains(activeView.frame) { | |
self.view.frame.origin.y = -keyboardSize.height | |
} | |
} | |
// shifts the view up for space for the keyboard | |
NotificationCenter.default.addObserver(forName: .UIKeyboardWillHide, object: nil, queue: nil) { | |
notification in | |
// move back to original position | |
self.view.frame.origin.y = 0 | |
} | |
} | |
// Make the keyboard disappear once return is pressed | |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { | |
textField.resignFirstResponder() | |
// Note: implements default return key behavior | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment