Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - close keyboard when button is pressed

Tags:

xcode

ios

swift

I currently have a textfield, a picker, a button, and several textviews/labels.

The textfield prompts a number only keyboard, I want the keyboard to dismiss when the one button is pressed.

Here is a snippet of some of the code:

class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate  {

    @IBOutlet weak var provincePicker: UIPickerView!

    @IBOutlet weak var calcButton: UIButton!

    @IBOutlet weak var incomeLabel: UITextView!

    @IBOutlet weak var salaryTextField: UITextField!
    @IBOutlet weak var beforeTax: UITextView!
    @IBOutlet weak var provincialTax: UITextView!
    @IBOutlet weak var federalTax: UITextView!
    @IBOutlet weak var afterTax: UITextView!

...

    override func viewDidLoad() {
  //  numberOnly()
         borders()
         super.viewDidLoad()
         provincePicker.dataSource = self
         provincePicker.delegate = self
    }

...

     @IBAction func calculateButton(sender: UIButton) {
         let formatter           = NSNumberFormatter()
         formatter.numberStyle   = NSNumberFormatterStyle.CurrencyStyle
         formatter.locale        = NSLocale(localeIdentifier: "en_CA")

         let index = provincePicker.selectedRowInComponent(0)

         switch(index) {
         case 0:
            calculate(abBrackets, rates: abRates)   //AB
         //cutting out code here
         dismissKeyboard()
      }

      func dismissKeyboard() {
         self.view.endEditing(true)
      }
like image 663
Arthur Avatar asked Dec 05 '25 10:12

Arthur


1 Answers

Try to call this function when your button is pressed:

    func dismissKeyboard() {
        self.view.endEditing(true)
    }

Or, in your button function, do this:

@IBAction func button(sender: UIButton) {
    self.view.endEditing(true)
}

And remember to connect your button to your viewController by control + click on your button and drag it to your controller file, then, on the popup, click on connection and select action and give it a name:

enter image description here

Also, check if you have multiple connection on your button, it might be a problem...

like image 134
Thomas Avatar answered Dec 08 '25 00:12

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!