这是我在启用键盘时向上移动按钮的代码:
@IBOutlet var lastNameText: HoshiTextField!
@IBOutlet var firstNameText: HoshiTextField!
override func viewDidLoad() {
var fab = MDCFloatingButton()
fab.translatesAutoresizingMaskIntoConstraints = false
fab.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant:-30.0).isActive = true
fab.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant:-240.0).isActive = true
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:.UIKeyboardWillShow, object: nil )
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:.UIKeyboardWillHide, object: nil)
@objc func keyboardWillShow(notificaion: NSNotification) {
if let keyboardSize = (notificaion.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{
//fab = UIButton(frame: CGRect(10+20, self.view.frame.size.height - keyboardSize.height - 40,80,30))
fab.frame = CGRect(x: 320, y: 350, width: 60, height: 60)
}
}
@objc func keyboardWillHide(notification: NSNotification ) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{
fab.frame = CGRect(x: 320, y: 350, width: 65, height: 65)
}
}
请输入。
最佳答案
首先,在您的类中添加textfield委托方法,然后简单地将此代码放入并根据您的要求进行更改:-
func textFieldDidBeginEditing(_ textField: UITextField) {
switch textField {
case txtFldSponsorID:
moveTextfield(textfield: txtFldSponsorID, moveDistance: 0, up: true)
case txtFldFullName:
moveTextfield(textfield: txtFldFullName, moveDistance: -10, up: true)
case txtFldEmail:
moveTextfield(textfield: txtFldEmail, moveDistance: -10, up: true)
case txtFldMobile:
moveTextfield(textfield: txtFldMobile, moveDistance: -10, up: true)
case txtFldAddress:
moveTextfield(textfield: txtFldAddress, moveDistance: -80, up: true)
case txtFldCity:
moveTextfield(textfield: txtFldCity, moveDistance: -80, up: true)
default:
break
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
switch textField {
case txtFldSponsorID:
moveTextfield(textfield: txtFldSponsorID, moveDistance: 0, up: true)
case txtFldFullName:
moveTextfield(textfield: txtFldFullName, moveDistance: 10, up: true)
case txtFldEmail:
moveTextfield(textfield: txtFldEmail, moveDistance: 10, up: true)
case txtFldMobile:
moveTextfield(textfield: txtFldMobile, moveDistance: 10, up: true)
case txtFldAddress:
moveTextfield(textfield: txtFldAddress, moveDistance: 80, up: true)
case txtFldCity:
moveTextfield(textfield: txtFldCity, moveDistance: 80, up: true)
default:
break
}
}
关于ios - 启用键盘时向上移动按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48759971/