我已经构建了一个基本的媒体播放器应用程序。 我有一个 tableView,其中列出了播客。 在行项目中,我列出了播客标题。 我还使用detailTextLabel 列出当前播放时间的倒计时。
一切正常,除了当我滚动 tableView 时单元格会重新加载并且我无法再更新时间。
如何保留对单元格的引用,以便即使在滚动后也可以更新单元格文本?
这是相关的代码片段......
var myCell = UITableViewCell()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
.... cell code
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
myMP.nowPlayingItem = qryPodcasts.items![indexPath.row]
if myMP.playbackState != MPMusicPlaybackState.Playing {
myMP.play()
}
// Grab a reference to the selected item
// for displaying elapsed time
myCell = tableView.cellForRowAtIndexPath(indexPath)!
}
func startTimer(){
myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(View_Podcast_List.updateTimer), userInfo: nil, repeats: true)
}
func stoptimer(){
myTimer.invalidate()
}
func updateTimer(){
let nowPlayingItemDuration = myMP.nowPlayingItem?.valueForProperty(MPMediaItemPropertyPlaybackDuration) as! Double
let remainingTime = nowPlayingItemDuration - myMP.currentPlaybackTime ;
myCell.detailTextLabel?.text = CommonFuncs.secondsToTime(Int(remainingTime))
}
最佳答案
您可以在计时器回调本身中调用 cellForRowAtIndexPath。然后你有两种可能性: cellForRowAtIndexPath 返回 nil,所以它不在屏幕上,所以没有什么可做的。或者它返回不为零,然后你更新它。
确保在 cellForRowAtIndexPath 委托(delegate)方法中设置正确的时间,以防当该行不在屏幕上时您错过了一些更新。
尝试保存对单元格的引用是行不通的。它可以防止单元被释放,但不能防止它被其他单元重复使用。
关于swift - 如何维护对表格 View 单元格的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250787/