首页 > 解决方案 > UITableView 中的预览标签运行两次

问题描述

我想在 UITableView 中创建一个预览标签,该标签每隔几秒钟就会自动更改一次,并带有淡入淡出的动画。问题是,当我转到另一个 ViewController 时,异步在后台继续,当我回来太快时,预览会运行两次。我该如何解决?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! startCell
    
    var previews = ["preview1", "preview2", "preview3", "preview4"]
    var chosenPreview: String?
    cell.previewLabel!.text = "\"\(previews[Int.random(in: 0...previews.count)])\""
    
    func changePreview() {
        
        guard self.isViewLoaded && (self.view.window != nil) else {
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + Double.random(in: 3...7)) {
            
            UIView.animate(withDuration: 0.5, animations: {
                cell.previewLabel.alpha = 0
            }) { _ in UIView.animate(withDuration: 1, animations: {
                func randomPreview() {
                    var random = previews[Int.random(in: 0...preview.count)]
                    if random == chosenPreview {
                        randomPreview()
                    } else {
                        chosenPreview = random
                    }}
                
                randomPreview()
                cell.previewLabel!.text = "\"\(chosenPreview!)\""
                cell.previewLabel.alpha = 1
                
            }) { (_) in
                changePreview()
            }
            }
            changePreview()
        }
        return cell
    }
}

标签: swiftuitableviewuikit

解决方案


推荐阅读