ios - 启用键盘时向上移动按钮

标签 ios swift uibutton material-design nsnotifications

这是我编写的用于在启用键盘时向上移动按钮的代码:

@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)
    }
}

请提供意见。

最佳答案

已更新至 Swift 4.+

viewDidLoad

//  Moving next button when keyboard appears
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name:UIResponder.keyboardWillHideNotification, object: nil)

显示键盘时:

@objc func keyboardWillShow(notification:NSNotification){
    let userInfo = notification.userInfo!
    var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    keyboardFrame = self.view.convert(keyboardFrame, from: nil)
    self.buttonNextBottomConstraint.constant = keyboardFrame.size.height
}

隐藏键盘时:

@objc func keyboardWillHide(notification:NSNotification){
    self.buttonNextBottomConstraint.constant = 0
}

关于ios - 启用键盘时向上移动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759971/

相关文章:

ios - 观察另一个类属性

iOS 6 和 iOS 7 UIButton 标签垂直对齐

iphone - 圆形图像按钮 VS 方形 Controller

ios - 在 Storyboard 中为 UIButton 设置边框

ios - 如何以下列格式向 NSDictionary 添加元素?

iOS - 关于 setAlpha 的导入与前向声明

ios - 可将表格菜单扩展到 Xcode 中的新 View Controller

ios - 如何让这个 segue 动画退出到右侧或左侧? - swift

ios - 链接到应用商店中另一个应用的正确方法是什么?

ios - 手动格式化