Friday, July 1, 2016

iOS Swift 키보드 show/hide 시 UI 위치 보정 처리

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        registerForKeyboardNotifications()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        unregisterForKeyboardNotifications()
    }

    //MARK: Keyboard events
    func registerForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)
    }

    func unregisterForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func keyboardWillShow(note: NSNotification) {
        // UI 키보드 위로 올려준다
        print("keyboardWillShow")

        let s = note.userInfo![UIKeyboardFrameEndUserInfoKey]
        let rect = s!.CGRectValue()
        
        // 입력창 위치를 올려줌
        var frame = textField.frame
        frame.origin.y -= rect.height
        textField.frame = frame

        let keyboardFrameEnd = view!.convertRect(rect, toView: nil)
        view.frame = CGRectMake(0, 0, keyboardFrameEnd.size.width, keyboardFrameEnd.origin.y)
        view.layoutIfNeeded()
    }
    
    func keyboardWillHide(note: NSNotification) {
        // UI 원위치 한다
        print("keyboardWillHide")

        let s = note.userInfo![UIKeyboardFrameBeginUserInfoKey]
        let rect = s!.CGRectValue()

        var frame = textField.frame
        frame.origin.y += rect.height
        textField.frame = frame
        
        frame = view.frame
        view.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, frame.height + rect.height)
        view.layoutIfNeeded()
    }

No comments:

Post a Comment