简体   繁体   中英

Dismiss Keyboard when editing UItextfield on Swift

i want to make a calculator with two textfield. there are numbers buttons and mathematical operations buttons. but i couldn't dismiss keyboard when clicking textfield. i never want to show keyboard but, want to edit textfield with numbers buttons.

touchbegans or textFieldShoulBeginEditing method didn't worked for me.

An answer to your question on how to dismiss the keyboard in Xcode 6.1 using Swift below:

import UIKit

class ItemViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textFieldItemName: UITextField!

    @IBOutlet var textFieldQt: UITextField!

    @IBOutlet var textFieldMoreInfo: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

        textFieldItemName.delegate = self
        textFieldQt.delegate = self
        textFieldMoreInfo.delegate = self
    }

                       ...

    /**
     * Called when 'return' key pressed. return NO to ignore.
     */
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


   /**
    * Called when the user click on the view (outside the UITextField).
    */
   override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
   }

}

( Source of this information ).

Edit

This workaround was specific for the above question , so stop downvote this answer. This is not about simply dismissing the keyboard. This is about being able to edit the textfield with custom inputView and make the textfield editable when there is no keyboard visible.

This makes your textfields keyboard disappear and still editable .

Objective-C

yourTextField.inputView = [[UIView alloc] initWithFrame:CGRectZero];

Swift

yourTextField.inputView = UIView(frame: CGRectZero)

Try this

self.endEditing = YES; 

In your ViewController

I've got solution from Ezimet 's answer

For Swift 5

myTextField.inputView = UIView(frame: CGRect.zero)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM