Touches began Func not working on scrollView

can't make the text disappeared when the user tap the screen in view inside scroll view

h ttps://i.stack.imgur.com/5l5if.png


outlets for the UIscrollView and UIImage

@IBOutletvar elskroll: UIScrollView!
@IBOutletvar elfondou: UIImageView!



text not dissmissing

overridefunc touchesBegan(_ touches: Set, with event: UIEvent?) {
        elskroll.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


not errors appeard

I don't understand : can't make the text disappeared when the user tap the screen in view inside scroll view

Which view ? It seems to contain a button and an image only ; unless there is also a textField not shown on the image ?

Where is the text ? Inside a textField ? Where is it declared ?


elskroll is a UIScrollView

So with,

elskroll.endEditing(true)

elskroll resigns as first responder, but that does not hide anythings (except keyboard is visible) ; so even if there is a textField inside the view, that will not make the text disappear


Why would it call textFieldShouldReturn(_ textField: UITextField)

Why would it make the text diapeear ?

-> Do you mean clear the text field ? : then set text to "" : myTextField.text = ""

-> Do you mean hide it ? : then set isHidden true : myTextField.isHidden = true


Note: have you a typo:

overridefunc touchesBegan(_ touches: Set, with event: UIEvent?) {

vs

override func touchesBegan(_ touches: Set, with event: UIEvent?) {


Seems you have not copied the exact code but retyped it ?

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        elskroll.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }



elskroll is the UIScrollView

@IBOutletvar elskroll: UIScrollView!


i have the Default View, inside a ScrollView and inside of a View


as the image shows

h ttps://i.stack.imgur.com/5l5if.png

Sorry, you do not answer my questions. That only repeats the original post.


Where is the text you want to make disappear ? Inside a textField ? Where is this textField declared ?


What is the Default View you mention ?


elskroll is the UIScrollView

@IBOutlet var elskroll: UIScrollView!


Yes, I understood this, but that does not answer the questions:

elskroll resigns as first responder, but that does not hide anythings (except keyboard is visible) ; so even if there is a textField inside the view, that will not make the text disappear


  • Why would it call textFieldShouldReturn(_ textField: UITextField)
  • Why would it make the text diapeear ?

Where is the text you want to make disappear ? Inside a textField ? Where is this textField declared ?


i want the keyboard to disappear when the user tap the screen (user only can see the keyboard when tap UITextField


What is the Default View you mention ?


maybe it was silly to mention Default 'view' what i meant for that is when you create a 'View Controller' comes with a blank screen and if you see it in the 'Document Outline it says


View Controller Scene

View Controller

View

Safe Area

First Responder

Exit


Why would it call textFieldShouldReturn(_ textField: UITextField)

i don't know i as far as i know i should put those two to make the text disappear and call it back (i read it in some place and always do it)


Why would it make the text disappear ?

i just want the keyboard to disappear not text

OK. What you want is the keyboard to disappear, but not the text with the code you've shown. Your original post was not clear.


Question: why did the keyboard appear ? Probably because you typed in a textField (let's name it myTextField) defined with an IBOutlet.


To hide the keyboard, you should call

myTextField.resignFirstResponder().


You could also call

textFieldShouldReturn(myTextField)

But not very useful

Usually, touch events on a UIScrolView are not forwarded to the encosing UIViewController.

(You know UIScrollView needs to handle touch events for scrolling.)


Have you checked your `touchesBegan(_:with:)` is ever called?


If no (it's the expected behavior as for now), you need to make some extra effort to detect touches on the UIScrollView.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { // All paths through this function will call itself


do i need to call every UITextField?

because i have several texts fields


like you said

To hide the keyboard, you should call

myTextField.resignFirstResponder().


You could also call

textFieldShouldReturn(myTextField)



Heres all my code to make it clear


import UIKit
import Alamofire

class crearchoferViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    
    var pasajero = true
    var nivel = "1"
    var iconClick : Bool!
    @IBOutlet var nombreConductor: UITextField!
    @IBOutlet var email: UITextField!
    @IBOutlet var password: UITextField!
    @IBOutlet var confirmarpass: UITextField!
    @IBOutlet var telefono: UITextField!
    @IBOutlet var telefonoContacto: UITextField!
    @IBOutlet var emailContacto: UITextField!
    @IBOutlet var ciudad: UITextField!
    @IBOutlet var direccion: UITextField!
    @IBOutlet var matricula: UITextField!
    @IBOutlet var licencia: UITextField!
    @IBOutlet var numeroTaxi: UITextField!
    @IBOutlet var tipoVehiculo: UITextField!
    @IBOutlet var year: UITextField!
    @IBOutlet var marcaCarro: UITextField!
    @IBOutlet var warningFoto: UILabel!
    @IBOutlet var image: UIImageView!
    @IBOutlet var elskroll: UIScrollView!
    @IBOutlet var elfondou: UIImageView!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        iconClick = true
        
       
    }
    
    
    @IBAction func gotocasita(_ sender: UIButton) {
        
         performSegue(withIdentifier: "deConductorACASITA", sender: self)
    }
    class func convertBase64ToImage(imageString: String) -> UIImage {
        let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
        return UIImage(data: imageData)!
    }
    
    
    @IBAction func crearCuenta(_ sender: UIButton) {
        
        if nombreConductor.text == "" || email.text == "" || password.text == "" || confirmarpass.text == "" || telefono.text == "" || telefonoContacto.text == "" || emailContacto.text == "" || ciudad.text == "" || direccion.text == "" || matricula.text == "" || licencia.text == "" || numeroTaxi.text == "" || tipoVehiculo.text == "" || year.text == "" || marcaCarro.text == "" {
            displayAlert(title: "Información Faltante", message: "Debes porporcionar los datos solicitados")
        }
        if password.text != confirmarpass.text {
            displayAlert(title: "Usuario", message: "Las contraseñas no coinciden")
        }
        
            
        else{
            /*
            //Use image name from bundle to create NSData
            let image : UIImage = UIImage(named:"info")!
            //Now use image to create into NSData format
            let imageData:NSData = image.pngData()! as NSData
            let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
            print(strBase64)  */
            
            
   
            let request = NSMutableURLRequest(url: NSURL(string: ":DDDDD")! as URL)
            request.httpMethod = "POST"
            let postString = "Nombre_Completo=\(nombreConductor.text!)&Correo=\(email.text!)&Password=\(password.text!)&Telefono=\(telefono.text!)&Email_Contacto=\(emailContacto.text!)&Telefono_Contacto=\(telefonoContacto.text!)&Nivel=\(nivel)&Ciudad=\(ciudad.text!)&Direccion=\(direccion.text!)&Matricula=\(matricula.text!)&Licencia=\(licencia.text!)&N_taxi=\(numeroTaxi.text!)&Tipo_Vehiculo=\(tipoVehiculo.text!)&Marca_Vehiculo=\(marcaCarro.text!)&Year=\(year.text!)&Foto=\(image!)"
            request.httpBody = postString.data(using: String.Encoding.utf8)
            
            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in
                
                if error != nil {
                    print("error=\(String(describing: error))")
                    
                    
                    return
                }
                
                print("response = \(String(describing: response))")
                
                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("responseString = \(String(describing: responseString))")
                
                
            }
            task.resume()
        }
      }

    @IBAction func selecFoto(_ sender: UIButton) {
    
    let imageController = UIImagePickerController()
        imageController.delegate = self
        imageController.sourceType = UIImagePickerController.SourceType.photoLibrary
        self.present(imageController, animated: true, completion: nil)
        
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        image.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        self.dismiss(animated: true, completion: nil)
       
}
    
   

    //ver la pazz con el boton
    @IBAction func verpazz(_ sender: UIButton) {
        let userPazzword = password.text!;
        
        if(iconClick == true) {
            password.isSecureTextEntry = false
            confirmarpass.isSecureTextEntry = false
            iconClick = false
        } else {
            password.isSecureTextEntry = true
            confirmarpass.isSecureTextEntry = true
            iconClick = true
        }
    }
    
    //funcion para el teclado que regrese
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        nombreConductor.resignFirstResponder()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textFieldShouldReturn(nombreConductor)
        return true
    }
    func displayAlert (title:String, message:String){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    
    
    
    
    
    
    
    
    //ultimo }
}
Accepted Answer

thanks i did some research and got it working


override func viewDidLoad() {
        super.viewDidLoad()
        iconClick = true
        
        // Do any additional setup after loading the view.
       
        let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.touch))
        recognizer.numberOfTapsRequired = 1
        recognizer.numberOfTouchesRequired = 1
        elskroll.addGestureRecognizer(recognizer)
        
        
        
        
    }
    
    @objc func touch() {
        self.view.endEditing(true)
    }
Touches began Func not working on scrollView
 
 
Q