这里有一个UICollectionView的大问题: 线程1:EXC_BREAKPOINT(代码= 1,子代码= 0x100434d10)
我希望让AVSpeechSynthesizer迭代UICollectionViewCells,以便说出并突出显示我在自定义UIcollectionViewCells中的标签内容,这些内容效果相当好。 如果我加载viewController并按下按钮来读取所有单元格,它可以正常工作。 现在如果我滚动一点(向下一个或两个单元格)并按下相同的按钮,应用程序崩溃。
我不知道造成这种情况的原因。 有人可以帮我解决这个问题吗? 这是我的代码:
@IBAction func playPauseButton(_ sender: UIButton) {
if !self.speechSynthesizer.isSpeaking{
let btnImage = UIImage(named: "pausedButton.png")
self.playPauseButton.setImage(btnImage , for: UIControlState.normal)
self.isPaused = false
self.shouldStopReading = false //triggered only if stop is pressed
var count = 0
var indexPath = NSIndexPath(row: 0, section: 0)
self.collectionView.selectItem(at: indexPath as IndexPath, animated: true, scrollPosition: .top)
isAutoPlaying = true
currentSelectedRow = 0
scrollAndSpeak(at: currentSelectedRow!)
}
}
func scrollAndSpeak(at index: Int) {
if index < self.wordList.count{
if self.shouldStopReading == false{
let indexPath = IndexPath(row: index, section: 0)
self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
let cell = self.collectionView.cellForItem(at: indexPath) as! CollectionViewCell
self.speakString(sender: self, str: (cell.label.text!)) //Speech
}
}
}
func speakString(sender: AnyObject,str:String) {
let utterance = AVSpeechUtterance(string: str)
utterance.rate = self.speechRate
utterance.voice = AVSpeechSynthesisVoice.init(language: "en_US")
speechSynthesizer.speak(utterance)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange:
NSRange, utterance: AVSpeechUtterance) {
let font = UIFont.systemFont(ofSize: 25)
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for:indexPath as IndexPath ) as! CollectionViewCell
let mutableAttributedString = NSMutableAttributedString (string : cell.label.text!)
mutableAttributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.blue, range:characterRange)
mutableAttributedString.addAttribute(NSFontAttributeName, value: font, range: characterRange)
cell.label.attributedText = mutableAttributedString;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath) as! CollectionViewCell
myCell.label.text = self.wordList[indexPath.row]
//collectionView.cel
return myCell
}