iOS/UIKIT

서치바를 눌렀을 때 서치바 y축 위치를 조절하는 방법

밤새는 탐험가89 2024. 10. 11. 05:59

서치바를 눌렀을 때 mapSearchView의 높이를 올려서 키보드가 서치바를 가리지 않도록 하려면, 서치바가 활성화될 때 mapSearchView의 높이를 변경하는 코드를 추가하면 됩니다. 또한, 키보드가 나타날 때 높이를 조정해주는 것이 필요합니다. 아래 방법으로 수정할 수 있습니다:

 

 

1. searchBarTextDidBeginEditing에서 높이 조정

서치바가 눌렸을 때 mapSearchView의 높이를 조정합니다. 이 코드는 이미 구현된 부분에 추가합니다.

 

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    // SearchBar가 활성화되면 높이를 400으로 변경
    UIView.animate(withDuration: 0.3) {
        self.mapSearchView.mapSearchViewHeightConstraint.constant = 400
        self.view.layoutIfNeeded()
    }
}

 

 

 

2. 키보드가 나타날 때 높이 조정

키보드가 올라올 때 높이를 조정하고, 사라질 때 다시 원래 높이로 조정하는 방식도 함께 처리할 수 있습니다. 이를 위해 NotificationCenter를 이용해 키보드가 나타나는 시점에 높이를 변경하는 것이 좋습니다.

 

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // 키보드가 나타날 때와 사라질 때 노티피케이션 등록
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // 노티피케이션 해제
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardHeight = keyboardSize.cgRectValue.height
        UIView.animate(withDuration: 0.3) {
            self.mapSearchView.mapSearchViewHeightConstraint.constant = keyboardHeight + 50 // 키보드 위로 여유 공간 추가
            self.view.layoutIfNeeded()
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    // 키보드가 사라지면 원래 높이로 돌아옴
    UIView.animate(withDuration: 0.3) {
        self.mapSearchView.mapSearchViewHeightConstraint.constant = 200 // 초기 높이로 조정
        self.view.layoutIfNeeded()
    }
}