多个UITextField
,软键盘显示和UIButton
在单击一个UITextField
时向上移动。
单击空白区域时,键盘关闭。
现在显示键盘,单击另一个UITextField
,向下移动UIButton
,此时键盘仍显示,我不想让UIButton
下移。
为什么键盘显示时UIButton
下移?
Gif屏幕截图
UIButton
下移。UIButton
仍在下面。UITextField
,UIButton
将从新版本上移下面是代码
class LoginPasswordViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var phoneInput: UITextField! // this is the first UITextField
@IBOutlet weak var passwordInput: UITextField! // this is the second UITextField
@IBOutlet weak var btnOK: UIButton! // this is the UIButton, it move up when Soft keyboard show.
fileprivate var btnOKOriginY: CGFloat!
fileprivate var isShow: Bool?
override func viewDidLoad() {
super.viewDidLoad()
// observer keyboard show
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil)
// observer keyboard hide
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil)
}
@objc func keyboardWillHide(_ notification: Notification) {
btnOK.frame.origin.y = btnOKOriginY
isShow = false
}
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
print("btnOK.frame.origin.y = ", btnOK.frame.origin.y)
if isShow ?? false && btnOK.frame.origin.y != btnOKOriginY{
return
}
isShow = true
if btnOKOriginY == nil {
btnOKOriginY = btnOK.frame.origin.y
}
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
btnOK.frame.origin.y = btnOKOriginY - keyboardHeight
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
closeSoftKey()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
closeSoftKey()
return true
}
func closeSoftKey() {
phoneInput.resignFirstResponder()
passwordInput.resignFirstResponder()
}
}
答案 0 :(得分:0)
UIButton
通过swift
代码进行初始化,问题不再存在...
下面是代码,其他保持不变
var btnOK: UIButton!
func initUIButton() {
btnOK = UIButton(frame: CGRect(x: self.view.frame.width - 55 - 16,
y: self.view.frame.height - 55 - 32,
width: 55,
height: 55))
btnOK.setImage( imageLiteral(resourceName: "ic_next"), for: .normal)
self.view.addSubview(btnOK)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
initUIButton()
}