I must admit, I was rather hesitant when I started this challenge, as I wasn’t overly confident on the implementation of delegates. However, after re-reading the relevant sections, I found that the answers were all there in the text.
Firstly, I implemented the ‘willSpeakWord’ delegate method:
func speechSynthesizer(sender: NSSpeechSynthesizer, willSpeakWord characterRange: NSRange, ofString string: String) {
let myString = NSMutableAttributedString(string: string)
myString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: characterRange)
textField.attributedStringValue = myString
}
Then I disabled the textField after clicking the button:
@IBAction func speakIt(sender: NSButton) {
// Get typed-in text as a string
let string = textField.stringValue
if string.isEmpty {
print("string from \(textField) is empty", terminator: "")
} else {
speechSynth.startSpeakingString(string)
isStarted = true
self.textField.enabled = false
}
}
I re-enabled it when the speech had finished:
func speechSynthesizer(sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) {
isStarted = false
print("finishedSpeaking=\(finishedSpeaking)", terminator: "")
self.textField.enabled = true
}
It’s great that this book constantly encourages you to reinforce the aspects that you were starting to get fuzzy over…