BCLtd BCLtd - 4 years ago 193
Swift Question

AVSpeechSynthesisVoice Read From Button Label

I am wondering how to get the AVSpeechSynthesisVoice to read text from a button. I am rather new to Swift. However, I have the following reading from a string:

@IBAction func btnOption1Audio(sender: UIButton)
{
myUtterance = AVSpeechUtterance(string: "Hola")
myUtterance.rate = 1
synth.speakUtterance(myUtterance)
myUtterance.voice = AVSpeechSynthesisVoice(language: "es-ES")

}


But when I change it to something like this (reading the button text), it won't work. I am sure it is just a syntax issue though:

@IBAction func btnOption1Audio(sender: UIButton)
{
myUtterance = AVSpeechUtterance(string: btnOption1Tap.titlelabel.text)
myUtterance.rate = 1
synth.speakUtterance(myUtterance)
myUtterance.voice = AVSpeechSynthesisVoice(language: "es-ES")

}


Where am I going wrong?

Thanks in advance

Answer Source

It is not clear from your code what btnOption1Tap is. If it is an @IBOutlet to a UIButton, then you still have some issues.

titleLabel is a property that returns an Optional UILabel. It must be unwrapped before being used. Likewise, the text property of UILabel returns an Optional String which also must be unwrapped. You'd need to do something like:

if let buttontext = btnOption1Tap.titleLabel?.text {
    myUtterance = AVSpeechUtterance(string: buttontext)
    myUtterance.rate = 1
    synth.speakUtterance(myUtterance)
    myUtterance.voice = AVSpeechSynthesisVoice(language: "es-ES")
}

You probably want to speak the text associated with the UIButton that is the sender. In that case, you could just use the currentTitle property of UIButton and use the nil coalescing operator ?? to safely unwrap the Optional String:

myUtterance = AVSpeechUtterance(string: sender.currentTitle ?? "")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download