I don't succeed to highlight text utterance in SwiftUI. I've found examples of it only in UIKit.
In UIKit it is supposed to be var label: UILabel!
, but in SwiftUI label has to be String. I've tried to convert NSMutableAttributedString
into String
format, inside function, but it's complaining.
How to work it out with String
formats, so that it works in SwiftUI, too?
import AVFoundation
class Speaker: NSObject {
let synth = AVSpeechSynthesizer()
var label: String // <- problem
override init() {
super.init()
synth.delegate = self
}
func speak(_ string: String) {
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
utterance.rate = 0.4
synth.speak(utterance)
}
// Functions to highlight text
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let mutableAttributedString = NSMutableAttributedString(string: utterance.speechString)
mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.red, range: characterRange)
label.attributedText = mutableAttributedString
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
label.attributedText = NSAttributedString(string: utterance.speechString)
}
}