일반적으로 UIView 에서 UITextFiled사용시 bottom Constraint 값으로 키보드 올라올때 UITextFiled도 같이 올라가게 작업한다.

UIScrollView에서는 다른 방식으로 처리해야된다.

 

UIScrollView 이용시

deinit {
	NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification , object: nil)
	NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification , object: nil)
}

override func viewDidLoad() {
	super.viewDidLoad()
    
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)
	NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(noti: )) , name: UIResponder.keyboardWillHideNotification, object: nil)
}

// UIScrollView 키보드 만큼 올려기
// MARK: 키보드 처리
@objc func keyboardWillShow(noti: NSNotification) {
	//키보드의 높이를 가져오는 코드
	let notiInfo = noti.userInfo! as NSDictionary
	var keyboardFrame = notiInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        
	keyboardFrame = self.view.convert(keyboardFrame, from: nil)

	var contentInset:UIEdgeInsets = self.scrollView.contentInset
	contentInset.bottom = keyboardFrame.size.height
	self.scrollView.contentInset = contentInset    
    }
    
@objc func keyboardWillHide(noti: NSNotification) {
	let notiInfo = noti.userInfo! as NSDictionary
        
	let contentInset:UIEdgeInsets = UIEdgeInsets.zero
	self.scrollView.contentInset = contentInset
}

 

UIView 이용시

// UIView 키보드 만큼 올리기
@objc func keyboardWillShow(noti: NSNotification) {
	//키보드의 높이를 가져오는 코드
	let notiInfo = noti.userInfo! as NSDictionary
	let keyboardFrame = notiInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        
	let bottomSafeArea = UIApplication.getsafeAreaBottomMargin()
	let height = keyboardFrame.size.height
	self.bottomTextFieldConstant.constant = height - bottomSafeArea
        
	//애니메이션 추가 (View가 먼저 올라가서 키보드 올라오는 공백이 순간적으로 보이는 문제로 추가)
	let animationDuration = notiInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
        
		UIView.animate(withDuration: animationDuration, animations: { [weak self] in
            self?.view.layoutIfNeeded()
        }) { (Bool) in    
	}
}
    
@objc func keyboardWillHide(noti: NSNotification) {
	let notiInfo = noti.userInfo! as NSDictionary
	self.bottomTextFieldConstant.constant = 0
        
	let animationDuration = notiInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
	UIView.animate(withDuration: animationDuration, animations: { [weak self] in
		self?.view.layoutIfNeeded()
	}) { (Bool) in
            
	}
}

+ Recent posts