Skip to content

8085studio/ios-interact-with-keyboard

Repository files navigation

iOS 虛擬鍵盤控制

按下鍵盤上的「完成」後隱藏虛擬鍵盤

ViewController.swift 加入以下程式碼

func textFieldShouldReturn(textField: UITextField) -> Bool {
	textField.resignFirstResponder()
	return true
}

執行

enter image description here

使用手勢操作來隱藏虛擬鍵盤

ViewController.swift 加入以下程式碼

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
	self.view.endEditing(true)
}

執行

enter image description here

進入文字方塊輸入時向上移動畫面,結束時向下移動畫面

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
}

執行

enter image description here

參考資訊

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages