gpt4 book ai didi

ios - 如何防止更新UITableView中的单元格?

转载 作者:行者123 更新时间:2023-12-02 23:45:36 25 4
gpt4 key购买 nike

我有一个UITableView,它正在播放来自Internet的音频剪辑。正在使用单例助手播放音频剪辑。当用户点击单元格中的按钮时,音频剪辑开始,并且进度指示器显示已播放了多少音频剪辑,这是可行的。通过这个单例,我传入了一个更新进度块,该块在播放单元时对其进行更新。

但是,当我滚动浏览剪辑列表时,进度指示器将继续为其他UITableViewCells进行进度。我的猜测是当我在dequeueReusableCellWithIdentifier中调用cellForRowAtIndexPath时,它正在返回当前正在由音频播放单例更新的单元格。我该如何解决这个问题?

编辑:这里的主要问题是我在播放playButtonPressed中的声音后传递了进度块。我每0.5秒更新一次进度。换句话说,如果我在cellForRow中将进度设置为0或类似的东西,它将在0.5秒后设置回当前进度。

[[Singleton sharedInstance] playURL:url completionHandler:^{
cell.playButton.selected = NO;
} errorHandler:^{
cell.playButton.selected = NO;
} progressHandler:^(float progress) {
if (cell.playButton.selected) {
[cell.progressView setProgress:progress animated:YES];
}
}];

最佳答案

假设您正在使用自定义的UITableViewCell子类,可能最好的处理方法是在单元格类中覆盖prepareForReuse。在这里,您可以隐藏进度指示器,将其完全删除,将其重置为零,或者在您的应用中最有意义的设置:

override func prepareForReuse() {
super.prepareForReuse()
progressView.progress = 0 // Or otherwise reset the progress view
}

顾名思义, prepareForReuse刚好在将单元格从重用队列中取出以再次使用之前被调用。您可以使用它来使您的单元格返回到一种状态,在该状态下,可能已为特定索引路径完成了所有设置。

或者,根据您的设置,在每个单元退出队列时仅查看每个单元,然后根据当前是否是音频助手正在播放的剪辑的单元来重置进度指示器,这可能会更有意义。
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MyCell
if indexPath.row == audioPlayer.indexOfTrackBeingPlayed {
cell.progressView.progress = audioPlayer.currentProgress
} else {
cell.progressView.progress = 0
}
}

编辑:

您添加到问题中的更新块的问题在于,您正在捕获该块中的特定单元格,但是该单元格随后在表中的其他位置被重用。相反,您需要使用 indexPath从块内部获取单元格,因此它始终会获取正确的单元格。例如:
[[Singleton sharedInstance] playURL:url completionHandler:^{
MyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.playButton.selected = NO;
} errorHandler:^{
MyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.playButton.selected = NO;
} progressHandler:^(float progress) {
MyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell.playButton.selected) {
[cell.progressView setProgress:progress animated:YES];
}
}];

必须在每个块内执行此操作有点麻烦,但这是必需的。您可以通过定义一个便捷属性来使其更加整洁:
@property(nonatomic, readonly) MyCell *playingCell;

- (MyCell *)playingCell {
NSIndexPath *playingIndexPath = // get the index path of the playing item
return [self.tableView cellForRowAtIndexPath:playingIndexPath];
}

然后只需用 cell替换块中的 self.playingCell即可。

关于ios - 如何防止更新UITableView中的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32016323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com