Search code examples
iosswiftxcodexibcustom-keyboard

How to use custom delegate for xib in swift?


I want to use inputAccessoryView to add custom number buttons above the keyboard. And I have added the view. I have assigned the class CustomKeyboard to the xib file. Within the CustomKeyboard class file, I have connected the IBAction of the buttons. I have two textFields in my ViewController textField1 & textFiled2 & I have associated inputAccessoryView with textField1. When I am tapping on textField1 then my custom buttons are shown above the keyboard. My goal is when I tap on my custom button it should enter the value in textFild2. But I really don't have any idea how would I achieve this. Anybody has some idea plz help me out.

import Foundation
import UIKit
class CustomKeyboard:UIView {
    @IBAction func rowButtonAction(_ sender: UIButton) {
        print(sender.currentTitle)
    }
    
}

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var textField1: UITextField!
    @IBOutlet weak var textField2: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        let view = UINib(nibName: "CustomKeyboard", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
        textField1.inputAccessoryView = view//customView
        textField1.autocorrectionType = .no
        textField2.autocorrectionType = .no
    }
}

enter image description here


Solution

  • You can use delegates or closures to get call back from CustomKeyboard to ViewController. Example below uses delegate method and function rowTapped will be called when user taps on view.

    import Foundation
    import UIKit
    
    protocol CustomKeyBoardProtocol:AnyObject{
            fun rowTapped(title:String)
    }
    class CustomKeyboard:UIView {
    
    weak var delegate:CustomKeyBoardProtocol?
        @IBAction func rowButtonAction(_ sender: UIButton) {
            print(sender.currentTitle)
            delegate.rowTapped(title: sender.currentTitle)
        }
    
    }
    
    import UIKit
    class ViewController: UIViewController,  CustomKeyBoardProtocol{
        @IBOutlet weak var textField1: UITextField!
        @IBOutlet weak var textField2: UITextField!
        override func viewDidLoad() {
            super.viewDidLoad()
            let customView = UINib(nibName: "CustomKeyboard", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomKeyboard
            customView.delegate = self// he
            textField1.inputAccessoryView = customView//customView
            textField1.autocorrectionType = .no
            textField2.autocorrectionType = .no
        }
    
    
        func rowTapped(title:String){//it will be called on tap
        }
    }