UITableViewCellbutton标签在UISearchController中返回所需的IndexPath,而不是FetchedResultsController

我在Swift 2.0的Core Data项目的UITableView上实现了NSFetchedResultsController 。 另外,我有一个UISearchController实现。 除了我在自定义的UITableViewCellbutton上遇到的行为之外,一切都可以正常工作。

UISearchController处于活动状态时, customTableViewCell的button按照它们应该的方式工作。 如果在fetchedResultsController显示其结果时单击相同的button,则方法认为索引0是发件人,无论我单击哪个button。

 func playMP3File(sender: AnyObject) { if resultsSearchController.active { // ** THIS WORKS ** // get a hold of my song // (self.filteredSounds is an Array) let soundToPlay = self.filteredSounds[sender.tag] // grab an attribute let soundFilename = soundToPlay.soundFilename as String // feed the attribute to an initializer of another class mp3Player = MP3Player(fileName: soundFilename) mp3Player.play() } else { // ** THIS ALWAYS GETS THE OBJECT AT INDEX 0 ** let soundToPlay = fetchedResultsController.objectAtIndexPath(NSIndexPath(forRow: sender.tag, inSection: (view.superview?.tag)!)) as! Sound // OTHER THINGS I'VE TRIED // let soundToPlay = fetchedResultsController.objectAtIndexPath(NSIndexPath(forRow: sender.indexPath.row, inSection: (view.superview?.tag)!)) as! Sound // let soundToPlay: Sound = fetchedResultsController.objectAtIndexPath(NSIndexPath(index: sender.indexPath.row)) as! Sound let soundFilename = soundToPlay.soundFilename as String mp3Player = MP3Player(fileName: soundFilename) mp3Player.play() } } 

这里是我的cellForRowAtIndexPath的缩写版本,以显示我设置单元格的button:

 let customCell: SoundTableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! SoundTableViewCell if resultsSearchController.active { let sound = soundArray[indexPath.row] customCell.playButton.tag = indexPath.row } else { let sound = fetchedResultsController.objectAtIndexPath(indexPath) as! Sound customCell.playButton.tag = indexPath.row } // add target actions for cells customCell.playButton.addTarget(self, action: "playMP3file:", forControlEvents: UIControlEvents.TouchUpInside) 

我已经尝试了其他一些方法,例如将CGPoints转换为IndexPaths等,但没有多less好运。 当我点击模拟器中的button时,编译器中看起来有希望的所有东西都会崩溃。

感谢您的阅读。

更新安装Xcode 7.1,重新启动,清理caching,nucked派生数据,做了一个冷启动。

在许多情况下,标签将完成工作(比如获取Array的位置),并在这里获得很多选票,但据我所知,它们并不是一直工作。 感谢Mundi指点我一个更强大的解决scheme。

 // this gets the correct indexPath when resultsSearchController is not active let button = sender as! UIButton let view = button.superview let cell = view?.superview as! SoundTableViewCell let indexPath: NSIndexPath = self.tableView.indexPathForCell(cell)! let soundToPlay = fetchedResultsController.objectAtIndexPath(indexPath) as! Sound 

我已经尝试了其他一些方法,例如将CGPoints转换为IndexPaths等,但没有多less好运。

翻译点确实是最可靠的解决scheme。 这个答案包含正确的代码。