2016-01-01 38 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