ViewController.swift
加入以下程式碼
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
ViewController.swift
加入以下程式碼
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
ViewController.swift
加入以下程式碼
private var currentTextField: UITextField?
private var isKeyboardShown = false
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardWillShow:",
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardWillHide:",
name: UIKeyboardWillHideNotification,
object: nil)
}
func textFieldDidBeginEditing(textField: UITextField) {
currentTextField = textField
}
func keyboardWillShow(note: NSNotification) {
if isKeyboardShown {
return
}
if (currentTextField != textBottom) {
return
}
let keyboardAnimationDetail = note.userInfo as! [String: AnyObject]
let duration = NSTimeInterval(keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber)
let keyboardFrameValue = keyboardAnimationDetail[UIKeyboardFrameBeginUserInfoKey]! as! NSValue
let keyboardFrame = keyboardFrameValue.CGRectValue()
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.frame = CGRectOffset(self.view.frame, 0, -keyboardFrame.size.height)
})
isKeyboardShown = true
}
func keyboardWillHide(note: NSNotification) {
let keyboardAnimationDetail = note.userInfo as! [String: AnyObject]
let duration = NSTimeInterval(keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber)
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.frame = CGRectOffset(self.view.frame, 0, -self.view.frame.origin.y)
})
isKeyboardShown = false
}