0

I have looked at many examples of extensions, thought can't find this. I am simply trying to use extension to add a toolbar with buttons on top of keyboard in swift, but since extensions can't have stored values easily , is there a simple way to pass variables to the selector methods for each buttons target in extension ? For example, I want to pass data to save to database in done() when save is tapped.

import UIKit
import FirebaseDatabase


extension UIViewController: UITextViewDelegate {

    func addToolBar(textField: UITextView, mode: Int, ref: String , pkg: [String:Any]){
        //mode: detailmsges = 2 ; home = 1
        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.default
        toolBar.isTranslucent = true

        toolBar.tintColor = UIColor.gray
        let doneButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.done, target: self, action: #selector(donePressed))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        if mode == 1 {
            let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPressed))
            toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        } else if mode == 2 {
            toolBar.setItems([spaceButton, doneButton], animated: false)
        }
        toolBar.isUserInteractionEnabled = true
        toolBar.sizeToFit()
        textField.delegate = self
        textField.inputAccessoryView = toolBar
    }

//how can I receive the parameters that I get in addToolBar() here to save to DB?
    func donePressed(){

        view.endEditing(true)
    }

    func cancelPressed(){
        view.endEditing(true)
    }
}

then I use it like:

addToolBar(textField: myTextField, mode: 1, ref: "", pkg: [:])
TheBen
  • 3,410
  • 3
  • 26
  • 51

0 Answers0