---
# System prepended metadata

title: 鍵盤
tags: [iOS]

---

###### tags: `iOS`
# 鍵盤

## 鍵盤監聽、升降
註冊廣播
```objectivec=
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowReciver), name: UIWindow.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideReciver), name: UIWindow.keyboardWillHideNotification, object: nil)        
}
```

監聽並開放接口
```objectivec=
@objc fileprivate func keyboardWillShowReciver(notification: NSNotification) {
    let userInfo = notification.userInfo
    let keyboardFrame = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
    guard let size = keyboardFrame?.cgRectValue else { return }
    guard let duration = userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
    keyboardWillShow(duration: duration, height: size.height)
}

@objc fileprivate func keyboardWillHideReciver(notification: NSNotification){
    let userInfo = notification.userInfo
    guard let duration = userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
    keyboardWillHide(duration: duration)
}
    
func keyboardWillShow(duration: Double,height :CGFloat) {
}
    
    
func keyboardWillHide(duration: Double) {
}
```

接口使用 (鍵盤出現時，修改 scroll view 高度，消失時改回去)
```objectivec=
override func keyboardWillShow(duration: Double, height: CGFloat) {
    scrollViewBottom.constant = -(height)
}
    
override func keyboardWillHide(duration: Double) {
    scrollViewBottom.constant = 0
}
```

## 讓鍵盤消失
點擊鍵盤以外的地方，使鍵盤消失

### UIViewController
```objectivec=
extension UIViewController{
           
    //點鍵盤外 會隱藏鍵盤
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //點擊時關閉編輯狀態，即可關閉鍵盤
        view.endEditing(true) 
        print("UIViewController touchesBegan")
    }
}
```

### UIScrollView
UIScrollView 需要取得最上層的 UIViewController，所以先寫個擴展
```objectivec=
extension UIApplication {    

    class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return getTopViewController(base: nav.visibleViewController)

        } else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return getTopViewController(base: selected)

        } else if let presented = base?.presentedViewController {
            return getTopViewController(base: presented)
        }
        return base
    }
}
```


```objectivec=
extension UIScrollView {
           
    //點鍵盤外 會隱藏鍵盤
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //點擊時關閉編輯狀態，即可關閉鍵盤
        UIApplication.getTopViewController()?.view.endEditing(true)
        print("UIScrollView touchesBegan")
    }
}
```

