Swift键盘出现在文本字段中,无法正常运行

时间:2018-08-25 13:26:16

标签: ios swift

我试图创建当键盘出现时相应的文本字段应移至键盘顶部,这是我需要解决的两件事,在编辑时间文本字段到达起点时,我还需要在子类中使用以下代码,因为要获取由其他多个类引用的文本字段。

在这里,在我的代码下方

extension UIView {

    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindFromKeyboard(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc
    func keyboardWillChange(notification: NSNotification) {

        guard let userInfo = notification.userInfo else { return }

        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        })
    }
}  

在Viewdidload中

baseview.bindToKeyboard()

文本字段应返回

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.baseview.endEditing(true)
        return false
    }

2 个答案:

答案 0 :(得分:0)

您可以考虑使用此框架,它将为您提供很多帮助:
https://github.com/hackiftekhar/IQKeyboardManager

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

      IQKeyboardManager.shared.enable = true

      return true
    }
}

答案 1 :(得分:0)

完全正常。试试这个

// Start Editing The Text Field
func textFieldDidBeginEditing(_ textField: UITextField) {
    moveTextField(textField, moveDistance: -100, up: true)
}

// Finish Editing The Text Field
func textFieldDidEndEditing(_ textField: UITextField) {
    moveTextField(textField, moveDistance: -100, up: false)
}

// Hide the keyboard when the return key pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

// Move the text field in a pretty animation!
func moveTextField(_ textField: UITextField, moveDistance: Int, up: Bool) {
    let moveDuration = 0.3
    let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)

    UIView.beginAnimations("animateTextField", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(moveDuration)
    self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
    UIView.commitAnimations()
}