点击UITextView时允许操作

时间:2018-01-16 15:54:43

标签: swift uitextview action uitextviewdelegate sfspeechrecognizer

我希望能够在我的Swift iOS应用程序中有效地使用UITextView作为按钮。当我点击文本视图时,我不希望它是可编辑的,但我希望它能够更改文本视图的背景颜色并开始在应用程序中使用语音识别软件。我已经看到了其他类似的问题,但没有人回答这个具体问题。

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

    }

}

1 个答案:

答案 0 :(得分:2)

您可以使用UITextViewDelegate方法:textViewShouldBeginEditing

从此方法返回false以防止将此特定文本字段设为firstResponder并更改背景并开始语音识别。

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

不要忘记将UITextview的委托添加到自己:

speechTextView.delegate = self