내 textField가 FirstResponder가되어있을 때 버튼을 위로 이동하여 그대로 유지하려고합니다. 내 코드는 textField에서 타이핑을 시작하기 전까지 작동하고 버튼은 원래 위치, 즉 키보드 뒤쪽으로 되돌아갑니다. 같은스위프트 : 키보드 위의 버튼 이동 및 유지
내 코드 :
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(exchangeButton)
exchangeButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
exchangeButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
exchangeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true
exchangeButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
subscribeToShowKeyboardNotifications()
amountTextField.becomeFirstResponder()
}
@objc func keyboardDidShow(_ notification: Notification) {
let userInfo = notification.userInfo
let keyboardSize = userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue
let keyboardHeight = keyboardSize.cgRectValue.height
self.exchangeButton.frame.origin.y = self.exchangeButton.frame.origin.y - keyboardHeight
}
func subscribeToShowKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: .UIKeyboardDidShow, object: nil)
}
참고이 VC가있는 viewDidLoad에 becomeFirstResponder을 할당하여 출시 때 나는 즉시 becomeFirstResponder에 텍스트 필드를 싶습니다.
또한 UIKeyboardWillShow와 viewWillAppear을 사용하여 시도했습니다. 이러한 시나리오에서 내 버튼은 이전되지 않습니다.
내 참조 : this SO post