Swift - Call UIToolBar by buttonClick Event

450 Views Asked by At

In my viewController there are one button and textField. When use click on textField it fires didBeginEdit event and i can call a toolbar. This is my view :

MyView

When user click on textField it seems like below :

textFieldClicked

And My Swift code is below :

Class ViewController: UIViewController {



    @IBAction func btn(sender: AnyObject) {


        // i want to call ToolBar here ...


     }


    @IBOutlet weak var textFieldOutlet: UITextField!

    @IBAction func txtFieldBeginEdit(sender: AnyObject) {

        raiseToolBar(textFieldOutlet)

    }





    var datePicker : UIDatePicker!
      let ToolBar = UIToolbar()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


    func raiseToolBar(textField : UITextField)
    {
        self.datePicker = UIDatePicker(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.height , UIScreen.mainScreen().bounds.height / 3))

        self.datePicker.backgroundColor = UIColor.whiteColor()
        self.datePicker.datePickerMode = .Date
        textField.inputView = self.datePicker


        ToolBar.barStyle = .Default
        ToolBar.translucent = true
        ToolBar.tintColor = UIColor(red : 92/255, green : 216/255 ,blue : 255/255, alpha: 1 )
        ToolBar.sizeToFit()


        let done = UIBarButtonItem(title: "Tamam" , style: .Plain , target:  self, action:  #selector(ViewController.doneClick))
        let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target : nil , action: nil)
        let cancel = UIBarButtonItem(title: "İptal" , style: .Plain , target:  self, action:  #selector(ViewController.cancelClick))
       ToolBar.setItems([done , space , cancel], animated: true)
        ToolBar.userInteractionEnabled = true
        textField.inputAccessoryView = ToolBar

    }

    func doneClick()  {


    }
    func cancelClick()  {

    }




}

At this point there is no problem. Bu i want to call this UIToolBar by clic on the button(named btn). Under btnClick event i tried to send empty textField to raiseToolBar method but it also don't work. How can i edit my code to call ToolBar by buttonClick

**************** edit *****************

    textFieldOutlet.becomeFirstResponder()
    raiseToolBar(textFieldOutlet)

i solve like above. is it a clear way ?

1

There are 1 best solutions below

1
On

You can assign first responder to your text field like this inside your btn action:

textFieldOutlet.isFirstResponder = true