ios - 如何在指定时间后淡出 UICollectionViewCell

标签 ios swift uicollectionview

我希望 UICollectionViewCells 显示后 3 秒淡出或 8 秒淡出 - 就像潜望镜在直播中淡出消息一样。这是我的代码的相关部分:

override func cellForItem(at index: Int) -> UICollectionViewCell {
    // ...

    // Get the time interval since the message was posted
    let timeInterval = 11 - Date().timeIntervalSince(message.timestamp)

    // If within the last 3 seconds, begin a fade.
    if timeInterval <= 3, timeInterval > 0 {
        cell.alpha = CGFloat(1 - 3/timeInterval)
        cell.fadeAlpha(to: 0, duration: timeInterval) { finished in
            if finished {
                self.delegate?.removeMessage(withSectionController: self)
            }
        }
    } else if timeInterval <= 0 {
        // If 11 secs or more have passed, remove.
        self.delegate?.removeMessage(...)
        cell.alpha = 0
    } else {
        // Otherwise start a timer
        timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(removeMessage), userInfo: nil, repeats: false)
    }
    return cell
}


@objc private func removeMessage() {
    timer.invalidate()
    // In other code I have got the cell
    // This is a UIView animation that changes the alpha
    cell.fadeAlpha(to: 0, duration: 3) { finished in
        if finished {
            self.delegate?.removeMessage(...)
        } else {
            // This gets cancelled on other cells when removeMessage gets called on a cell.
        }
    }
}


// In the delegate
func removeMessage(...) {
    model.messages.removeFirst()
    // This performs updates on the collection view data
    performUpdates()
}

... 表示还有其他代码,但不相关。

我的代码可以工作,除非我的 Collection View 更新单元格,任何当前的淡入淡出都被取消。我该如何解决这个问题?

最佳答案

您应该将其实现为自定义 UICollectionViewLayout。显示后设置一个计时器以从模型中删除消息,并通过调用删除单元格

deleteItems(at: [IndexPath])

在您想要淡出的项目的 Collection View 上。

在您的自定义布局中,您将希望实现

finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes?

并返回一个 UICollectionViewLayoutAttributes 实例,并将 alpha 属性设置为 0。

此方法指定从 Collection View 中删除项目时将动画化的属性。

关于ios - 如何在指定时间后淡出 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597582/

相关文章:

ios - 我如何分发混合的 Objective-C 和 Swift 代码以在 iOS 模拟器上运行?

ios - 改变 CALayer 的旋转变换为一个值而不改变层的缩放变换

swift - Core Data 可选属性和具有 Swift 规则的属性

javascript - 如何将 NSArray 传递给 JavaScript 文件并在 JavaScript 中打印该数组?

ios - 使用 UISplitViewController 而不是仅创建具有 2 个 subview 的单个 UIViewController 有什么好处

ios - NSBundle不同文件夹下两张图片同名

iOS:知道哪个 UITableView Cell 被点击了

ios - 尝试使用 Swift 以编程方式显示 UIScrollView 而根本不显示

ios - 一个 View Controller 上的两个 CollectionView

ios - 尝试在手势识别时翻转单元格上的 ImageView ,代码工作正常但没有翻转