Search code examples
iosswiftxcode10swift4.2

set next Button & Done Button instead of return in keyboard swift 4


https://i.sstatic.net/yNZh1.gif

I need next button, previous button and done button when keyboard appears in toolbar I have implemented this code...

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

@IBOutlet weak var textfieldOne: UITextField!
@IBOutlet weak var textFieldTwo: UITextField!
@IBOutlet weak var textFieldThree: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

func setAccessoryViewFor(textField : UITextField)   {
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.sizeToFit()

    // Adds the buttons

    // Add previousButton
    let prevButton = UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(previousPressed(sender:)))
    prevButton.tag = textField.tag
    if getPreviousResponderFor(tag: textField.tag) == nil {
        prevButton.isEnabled = false
    }

    // Add nextButton
    let nextButton = UIBarButtonItem(title: ">", style: .plain, target: self, action: #selector(nextPressed(sender:)))
    nextButton.tag = textField.tag
    if getNextResponderFor(tag: textField.tag) == nil {
        nextButton.title = "Done"
    }

    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    toolBar.setItems([prevButton,spaceButton,nextButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    textField.inputAccessoryView = toolBar
}



@objc func nextPressed(sender : UIBarButtonItem) {
    if let nextResponder = getNextResponderFor(tag: sender.tag) {
        nextResponder.becomeFirstResponder()
    } else {
        self.view.endEditing(true)
    }

}

@objc func previousPressed(sender : UIBarButtonItem) {
    if let previousResponder = getPreviousResponderFor(tag : sender.tag)  {
        previousResponder.becomeFirstResponder()
    }
}

func getNextResponderFor(tag : Int) -> UITextField? {
    return self.view.viewWithTag(tag + 1) as? UITextField
}

func getPreviousResponderFor(tag : Int) -> UITextField? {
    return self.view.viewWithTag(tag - 1) as? UITextField
}

}

Any body please help...


Solution

  • You can register to keyboard appear/disappear events and can add a UIToolBar with your next & back buttons on top of it. Or else, just integrate this library and you're done with few lines of code.