2016-01-01 37 views
0

我想知道如何让AVSpeechSynthesisVoice从按钮读取文本。我对Swift很陌生。不过,我有以下的阅读从一个字符串:AVSpeechSynthesisVoice从按钮标签读取

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

    } 

但是,当我将其更改为这样的事情(阅读按钮上的文字),它不会工作。我相信这只是一个语法问题,但:

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

    } 

我要去哪里错了?

在此先感谢

回答

1

它是不是从你的代码是什么btnOption1Tap是明确的。如果它是@IBOutletUIButton,那么你仍然有一些问题。

titleLabel是一个属性,返回可选UILabel。在使用之前必须解开包装。同样,财产UILabel返回可选String它也必须展开。你需要做这样的事情:

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

你可能想说话与UIButton那是sender相关联的文本。在这种情况下,你可以只使用的UIButtoncurrentTitle性能和使用零合并运算??安全地解开了可选String

myUtterance = AVSpeechUtterance(string: sender.currentTitle ?? "") 
+0

感谢您的详细回答,这是非常赞赏。我现在要试一试。我对swift非常陌生,因此需要付出很多努力:) – BCLtd

+0

我的工作得到了您的帮助。谢谢! – BCLtd