1

I would like to be able to effectively use a UITextView as a button in my Swift iOS application. When I tap on the text view, I don't want it to be editable, but I want it to change the background color of the text view and begin using the speech recognition software in the app. I've seen some other questions similar to this, but none answering this specific question.

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
    guard textView == inView else {

        guard textView == resultView else {
            return false
        }

        nextButton.isEnabled = true

        return false

    }

    if audioEngine.isRunning {

        let myColor: UIColor = UIColor(red: 50, green: 0, blue: 0, alpha: 0.75)

        inView.layer.backgroundColor = myColor.cgColor
        audioEngine.inputNode.removeTap(onBus: 0)

        globalVariables.boolRecording = false
        audioEngine.stop()

        recognitionRequest?.endAudio()
        microphoneButton.isEnabled = true
        microphoneButton.setTitle("Start Recording", for: .normal)

        globalVariables.finalText = globalVariables.finalText + globalVariables.tempText
        globalVariables.tempText = ""

        self.inView.text = ""

        return false

    } else {

        let myColor: UIColor = UIColor(red: 0, green: 50, blue: 0, alpha: 0.75)

        inView.layer.backgroundColor = myColor.cgColor
        globalVariables.boolRecording = true
        startRecording()
        microphoneButton.setTitle("Stop Recording", for: .normal)

        return false

    }

}
aequinox
  • 125
  • 1
  • 17

1 Answers1

4

You can use UITextViewDelegate method:textViewShouldBeginEditing.

Return false from this method to prevent making this particular textfield firstResponder and change the background and start your speech recognition.

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
    guard textView == speechTextView else {
        return true
    }
    // Change bg
    speechTextView.backgroundColor = UIColor.blue
    // Start speech
    startSpeechRecognition()
    return false
}

Don't forget to add delegate of UITextview to self:

speechTextView.delegate = self
Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33
  • Thank you -- that is mostly working. However, I am trying to do this with two textviews, and the second textview, resultView will not work unless it is tapped twice. Why is that? See my code added above. – aequinox Jan 16 '18 at 18:56
  • @AEquinox01: You want same actions on tap of both textviews? – Puneet Sharma Jan 17 '18 at 05:35
  • No -- I would like two different actions for two different textviews. – aequinox Jan 17 '18 at 15:20