我没有成功在SwiftUI中突出显示文本话语。我仅在UIKit中找到了它的示例。在UIKit中应该为var label: UILabel!
,但在SwiftUI标签中必须为String。我试图转换NSMutableAttributedString
成String
内部函数格式,但是很抱怨。如何处理String
格式,使其也可以在SwiftUI中使用?
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)
}
}
我建议您进行包装UILabel
,UIViewRepresentable
以便可以像以前一样继续使用属性字符串:
struct ContentView : View {
@ObservedObject var speaker = Speaker()
var body: some View {
VStack {
LabelRepresented(text: speaker.label)
}.onAppear {
speaker.speak("Hi. This is a test.")
}
}
}
struct LabelRepresented: UIViewRepresentable {
var text : NSAttributedString?
func makeUIView(context: Context) -> UILabel {
return UILabel()
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.attributedText = text
}
}
class Speaker: NSObject, ObservableObject, AVSpeechSynthesizerDelegate {
let synth = AVSpeechSynthesizer()
@Published var label: NSAttributedString? // <- change to AttributedString
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 = mutableAttributedString
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
label = NSAttributedString(string: utterance.speechString)
}
}
我将其更改label
为,NSAttributedString?
并将其设置为@Published属性ObservableObject
,这样,当更改时,视图会立即得到通知。
在UIViewRepresentable
创建一个标签,并用属性串任何它改变时更新它。
如果您确实想尝试一种更纯粹的SwiftUI方法,此博客文章提供了一些在SwiftUI中使用NSAttributedString的良好资源(包括我采用的方法):https ://swiftui-lab.com/attributed-strings-with -swiftui /
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句