web-dev-qa-db-fra.com

iOS/Swift: comment détecter une action tactile sur un UITextField

Je souhaite détecter l'action tactile sur un UITextField.

Il semble que l'action "Retouche à l'intérieur" ne soit pas déclenchée en touchant dans le champ de texte.

22
Daniele B

Il semble que "Touch Up Inside" n'est pas activé pour UiTextField, mais "Touch Down" fonctionne.

La solution est donc la suivante:

myTextField.addTarget(self, action: #selector(myTargetFunction), for: UIControlEvents.touchDown)

@objc func myTargetFunction(textField: UITextField) {
    print("myTargetFunction")
}
44
Daniele B

Swift 4:

class ViewController: UIViewController, UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == myTextField {
            print("You edit myTextField")
        }
    }
}

Ceci est une fonction de délégué.

19
Jonas Deichelmann

voici Swfit:

et vous n'avez pas besoin d'utiliser "touchUpInside", utilisez simplement les méthodes de délégation comme ceci:

Faites de votre contrôleur View un délégué:

class ViewController: UIViewController, UITextFieldDelegate{

func textFieldDidBeginEditing(textField: UITextField) -> Bool {
    if textField == myTextField {
        return true // myTextField was touched
    }
}

Voici les autres méthodes de délégué:

protocol UITextFieldDelegate : NSObjectProtocol {

    optional func textFieldShouldBeginEditing(textField: UITextField) -> Bool // return NO to disallow editing.
    optional func textFieldDidBeginEditing(textField: UITextField) // became first responder
    optional func textFieldShouldEndEditing(textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
    optional func textFieldDidEndEditing(textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text

    optional func textFieldShouldClear(textField: UITextField) -> Bool // called when clear button pressed. return NO to ignore (no notifications)
    optional func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
}

des documents Swift:

struct UIControlEvents : RawOptionSetType {
    init(_ rawValue: UInt)
    init(rawValue: UInt)

    static var TouchDown: UIControlEvents { get } // on all touch downs
    static var TouchDownRepeat: UIControlEvents { get } // on multiple touchdowns (tap count > 1)
    static var TouchDragInside: UIControlEvents { get }
    static var TouchDragOutside: UIControlEvents { get }
    static var TouchDragEnter: UIControlEvents { get }
    static var TouchDragExit: UIControlEvents { get }
    static var TouchUpInside: UIControlEvents { get }
    static var TouchUpOutside: UIControlEvents { get }
    static var TouchCancel: UIControlEvents { get }

    static var ValueChanged: UIControlEvents { get } // sliders, etc.

    static var EditingDidBegin: UIControlEvents { get } // UITextField
    static var EditingChanged: UIControlEvents { get }
    static var EditingDidEnd: UIControlEvents { get }
    static var EditingDidEndOnExit: UIControlEvents { get } // 'return key' ending editing

    static var AllTouchEvents: UIControlEvents { get } // for touch events
    static var AllEditingEvents: UIControlEvents { get } // for UITextField
    static var ApplicationReserved: UIControlEvents { get } // range available for application use
    static var SystemReserved: UIControlEvents { get } // range reserved for internal framework use
    static var AllEvents: UIControlEvents { get }
}

UITextField ne répond pas à "touchUpInside" (voir à droite), vous constaterez qu'il s'agit d'événements de contrôle acceptables.

11
Loxx

Mise à jour pour Swift 3

Voici le code pour Swift 3:

myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)

C'est la fonction:

func myTargetFunction() {
    print("It works!")
}
9
Ibrahim

Je me suis référé à la documentation UIControlEvents de Apple et voici ce qui suit:

Ajoutez d’abord UITextFieldDelegate à votre classe puis,

textBox.delegate = self
textBox.addTarget(self, action: #selector(TextBoxOn(_:)),for: .editingDidBegin)
textBox.addTarget(self, action: #selector(TextBoxOff(_:)),for: .editingDidEnd)

avec les fonctions suivantes:

func TextBoxOff(_ textField: UITextField) {
     code
         }                
}

func TextBox(_ textField: UITextField) {
    code
         }
}
7
Craig P

Pour Swift 3.1:

1) Créer un identificateur de geste:

let textViewRecognizer = UITapGestureRecognizer()

2) Ajoutez un gestionnaire au dispositif de reconnaissance:

textViewRecognizer.addTarget(self, action: #selector(tappedTextView(_:))) 

3) Ajoutez le logiciel de reconnaissance à votre affichage texte:

textView.addGestureRecognizer(textViewRecognizer)

4) Ajoutez le gestionnaire à votre classe:

func tappedTextView(_ sender: UITapGestureRecognizer) {
        print("detected tap!")
}
6
drbobdugan

Version Swift 3.0:

textFieldClientName.addTarget(self, action: Selector(("myTargetFunction:")), for: UIControlEvents.touchDown)
3
Matheus Faleiro

Pour que cela soit un peu plus clair, ces éléments doivent être en place. Je l'ai utilisé pour faire en sorte que si un utilisateur saisit quelque chose dans une application de la zone de texte de crédit de mon propre document, tout élément de la zone de texte de débit est supprimé.

  1. UITextFieldDelegatedoit être déclaré dans le contrôleur de vue i.eclass SecondViewController: 
  2. Les fonctions du détecteurfunc myDebitDetector func myCreditDetectordoivent être dans la classe ViewController.
  3. putdebit.addTarget et credit.addtargetla vue intérieure apparaîtra.

  4. @IBOutlet faible débit var: UITextField!et@IBOutlet faible crédit var: UITextField!sont des champs de texte sur le storyboard et connectés au viewController.

    classe SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var credit: UITextField!
    
    @IBOutlet weak var debit: UITextField!
    
        func myDebitDetector(textfield: UITextField ){
            print("using debit")
            credit.text = ""
    
        }
    
        func myCreditDetector(textfield: UITextField) {
            print("using cedit")
            debit.text = ""
        }
    
        override func viewWillAppear(animated: Bool) {
    
    
    
            debit.addTarget(self, action: "myDebitDetector:", forControlEvents: UIControlEvents.TouchDown)
            credit.addTarget(self, action: "myCreditDetector:", forControlEvents: UIControlEvents.TouchDown)
        ....
    
        }
    }
    
3
Mountain Man

Définissez le délégué UITextField sur votre contrôleur de vue, implémentez la méthode delegate

-(void)textField:(UITextField*)textField didBeginEditing {
   // User touched textField
}
1
Lytic

Swift 4.2. 

Essayez .editingDidEnd au lieu de .touchDown et delegate .

myTextField.addTarget(self, action: #selector(myTargetFunction), for: .editingDidEnd)

@objc func myTargetFunction(textField: UITextField) {
    print("textfield pressed")
}
0
Andy