You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift iOS:点击UITextView触发语音识别及背景色切换的实现

解决方案:将UITextView作为按钮使用并实现语音识别切换

你的思路其实已经找对了核心方向——利用UITextViewDelegate的textViewShouldBeginEditing方法拦截编辑事件,转而执行自定义的按钮逻辑。下面帮你梳理并优化这段代码,确保功能稳定运行:

核心实现逻辑拆解

  • 拦截编辑状态:通过让textViewShouldBeginEditing返回false,直接禁止UITextView进入编辑模式,这是把它变成“按钮”的关键。
  • 状态可视化反馈:根据语音识别的运行状态(audioEngine.isRunning)切换背景色,让用户直观感知当前是录音中还是已停止。
  • 语音识别控制:在分支逻辑里处理录音的启动/停止,同步更新全局变量、按钮状态和文本内容。

优化后的完整代码

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
    // 仅处理目标文本视图inView
    guard textView == inView else {
        // 处理resultView的特殊逻辑:启用next按钮并禁止编辑
        if textView == resultView {
            nextButton.isEnabled = true
        }
        return false
    }
    
    if audioEngine.isRunning {
        // 停止录音流程
        let stopRecordingColor = UIColor(red: 50/255.0, green: 0, blue: 0, alpha: 0.75)
        inView.layer.backgroundColor = stopRecordingColor.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.tempText
        globalVariables.tempText = ""
        inView.text = ""
    } else {
        // 启动录音流程
        let startRecordingColor = UIColor(red: 0, green: 50/255.0, blue: 0, alpha: 0.75)
        inView.layer.backgroundColor = startRecordingColor.cgColor
        
        globalVariables.boolRecording = true
        startRecording()
        
        microphoneButton.setTitle("Stop Recording", for: .normal)
    }
    
    // 始终返回false,彻底禁止编辑状态
    return false
}

关键细节优化提示

  • 颜色值修正:原代码中UIColor的RGB参数用了整数(比如50),但UIColor的RGB范围是0-1,必须除以255.0才能显示正确的颜色。
  • 代码可读性:拆分了嵌套的guard语句,给颜色变量起了更直观的名字,让逻辑结构更清晰。
  • 代理绑定:别忘了在ViewController的viewDidLoad里设置inView.delegate = self,否则代理方法不会被触发。
  • 交互体验升级:可以给inView设置cursorColor = .clear隐藏光标,再加上isUserInteractionEnabled = true(默认开启,若之前禁用过需重新打开),让它看起来更像按钮而非输入框。

内容的提问来源于stack exchange,提问作者aequinox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:19:34