【发布时间】:2021-02-10 15:58:26
【问题描述】:
我没有成功在 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)
}
}
【问题讨论】:
标签: swift swiftui avfoundation