swift - 点击 UITextView 时允许操作

标签 swift uitextview action uitextviewdelegate sfspeechrecognizer

我希望能够在我的 Swift iOS 应用程序中有效地使用 UITextView 作为按钮。当我点击 TextView 时,我不希望它是可编辑的,但我希望它更改 TextView 的背景颜色并开始使用应用程序中的语音识别软件。我见过其他一些与此类似的问题,但没有一个能回答这个具体问题。

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

    }

}

最佳答案

您可以使用 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 的委托(delegate)添加到自身:

speechTextView.delegate = self

关于swift - 点击 UITextView 时允许操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285175/

相关文章:

ios - 在 superview 中限制水平和垂直居中会阻止我更改框架

ios - iOS 9.0 中的 UITextview 字体为零

c# - 如何将 void 返回扩展方法传递给动态返回扩展方法?

java - actionPerformed(ActionEvent e) {

ios - 显示带有操作的搜索栏(栏项)

swift - 准确获取 NSTextField 包装大小 (Swift)

swift - 更改 TextField 中的清除按钮

swift - 转到 UIPageViewController 中的下一页

ios - asyncAfter 不延迟指定时间的第一次执行

ios - 带有链接 : disable scrolling, 的 UITextView 已启用用户交互