我想在UICollectionViewCells显示后显示3秒或8秒 - 就像periscope如何淡出直播中的消息一样。这是我的代码的相关部分:
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()
}
...
表示还有其他代码但不相关。
我的代码有效,除非我的集合视图更新单元格,否则会取消当前的淡入淡出。我该如何解决这个问题?
答案 0 :(得分:0)
您应该将其实现为自定义UICollectionViewLayout。显示后,设置计时器以从模型中删除消息,并通过调用
删除单元格deleteItems(at: [IndexPath])
在您想要淡出的项目的集合视图中。
在自定义布局中,您需要实现
finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes?
并返回UICollectionViewLayoutAttributes
实例,并将alpha
属性设置为0。
此方法指定从集合视图中删除项目时将设置为的属性。