Move textfield when keyboard appears swift 4


Create viewController.swift in copy this code

import UIKit

class AppearsKeyViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var appears: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // KeyboardShow
    func textFieldDidBeginEditing(_ textField: UITextField) {
        moveTextField(textField: appears, moveDistance: -250, up: true)
    }
    
    // KeyboardHide
    func textFieldDidEndEditing(_ textField: UITextField) {
        moveTextField(textField: appears, moveDistance: -250, up: false)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        appears.becomeFirstResponder()
        
        return true
    }
    
    func moveTextField(textField: UITextField, moveDistance: Int, up: Bool) {
        let moveDuration = 0.3
        let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)
        
        UIView.beginAnimations("animationTextField", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(moveDuration)
        view.frame = view.frame.offsetBy(dx: 0, dy: movement)
        UIView.commitAnimations()
    }
}

for a simple way, use the following libraries  IQKeyboardManager

1. install cocoapod for Swift 4.0 (Xcode 9.0)

pod 'IQKeyboardManagerSwift'

2. in your appdelegate use this code

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

      IQKeyboardManager.sharedManager().enable = true

      return true
    }
}

or click this link

This my note as my problem and solution @luffyselah


No comments: