swift - 如何维护对表格 View 单元格的引用?

标签 swift uitableview

我已经构建了一个基本的媒体播放器应用程序。 我有一个 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/

相关文章:

ios - 防止转义 URL 中的括号

iphone - 如何正确更新表中部分中动态变化的行数(及其单元格内容)?

ios - SwiftUI 静态列表奇怪的重用行为

ios - 如何使用 Alamofire 发送表单数据主体

ios - 在 UITableview 内的自动调整大小的标签上设置非常非常长的文本会破坏 NSLayoutConstraint

ios - 恢复滚动位置uitableview

ios - 使用 PresentViewController 而不是 Storyboard 不会显示单元格数据?

ios - UITableView 和 UICollectionView 里面的scrollView不可见

ios - UITableViewCell 显示错误的字符串

ios - 从不同的pickerView中获取值(value)