본문 바로가기

프로그래밍/iOS,macOS

[iOS] 키보드를 따라 올라오는 뷰


해당 뷰의 bottom contraint 를 키보드 사이즈에 맞춰 변경(auto layout 을 사용하지 않는 경우 해당 뷰 프레임을 직접 변경) 

@IBOutlet weak var editView: NSLayoutConstraint!

 

키보드 이벤트 등록

NotificationCenter.default.addObserver(
    self, 
    selector: #selector(MyViewController.keyboardWillShow),
    name: UIResponder.keyboardWillShowNotification,
    object: nil)
    
NotificationCenter.default.addObserver(
    self,
    selector: #selector(MyViewController.keyboardWillHide),
    name: UIResponder.keyboardWillHideNotification,
    object: nil)

 

이벤트 발생시 constraint 조정

@objc func keyboardWillShow(notification: NSNotification) {
    keyboardShowHide(notification: notification)
}

@objc func keyboardWillHide(notification: NSNotification) {
    keyboardShowHide(notification: notification)
}

func keyboardShowHide(notification: NSNotification) {
    let userInfo = notification.userInfo!
    let animationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboardEndFrame = self.view.convert(keyboardFrame, from: swlf.view.window)
    let rawAnimationCurve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).uintValue << 16
    
    
    // ios 11 이상 safe area
    let safeArea = self.view.safeAreaLayoutGuide.layoutFrame.insetBy(dx: 0, dy: -additionalSafeAreaInsets.bottom)
    let intersection = safeArea.instersection(keyboardEndFrame)
    let height = intersection.height
    
    
    UIView.animate(
        withDuration: animationDuration, 
        delay: 0.0,
        options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.beginFromCurrentState.rawValue|rawAnimationCurve),
        animation: {
            self.editViewBottom.constant = height
            self.view.layoutIfNeeded()
        }, completion: nil)
        
}

 

엔터키 입력시 키보드 닫기

extention MyViewController: UITextFieldDelegate {
    func texFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.myTextField.resignFirstResponder()
        // or self.myTextField.endEditing(true)
        // or self.view.endEditing(true)
        return true
    }
}

 

배경 터치시 키보드 닫기

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}
 

'프로그래밍 > iOS,macOS' 카테고리의 다른 글

[Metal] Render to Texture  (0) 2020.12.27
UIButton selected + highlighted image  (0) 2020.12.02
CaptureSession 카메라, 마이크  (0) 2020.07.10
Codable for Dictionary  (0) 2020.06.10
UITableView , UICollectionView  (1) 2020.04.14
[iOS] Google SignIn  (0) 2020.03.30
xcode 11. ios13 미만, storyboard 없이 시작  (0) 2020.03.29
XCFramework 만들기  (0) 2020.03.27
[iOS] CoreAudio AudioUnit  (0) 2019.10.08
iOS 프레임워크 파이썬 스크립트  (0) 2019.07.23