在用户开始键入时将UIButton移至小键盘,可以通过以下步骤实现:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let buttonHeight = myButton.frame.size.height
let buttonY = keyboardSize.origin.y - buttonHeight - 10 // 10为按钮与键盘之间的间距
myButton.frame = CGRect(x: myButton.frame.origin.x, y: buttonY, width: myButton.frame.size.width, height: myButton.frame.size.height)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
// 恢复按钮原来的位置
myButton.frame = CGRect(x: originalX, y: originalY, width: myButton.frame.size.width, height: myButton.frame.size.height)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
这样,当用户开始键入时,UIButton就会根据键盘的弹出和收起事件进行相应的移动。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云