我希望 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/