如何更新之前和现在选择的 CollectionView 单元格 Swift 4?
How to update the CollectionView cell that selected before and now Swift 4?
我有一个横向 collection view.When 用户点击一张照片,一个 UIView 似乎覆盖了 photo.Only 1 照片将可以在 1 time.Means 中选择,如果选择了一张照片,如果我点击另一张照片,前一张照片将恢复正常。
我在下面实现了这段代码:
var previousSelectedIndexPath : IndexPath?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if previousSelectedIndexPath != nil {
let previousCell = collectionView.cellForItem(at: previousSelectedIndexPath!) as! photoCell
previousCell.uiViewHeight.constant = 0
}
let currentCell = collectionView.cellForItem(at: indexPath) as! photoCell
currentCell.uiViewHeight.constant = 250
previousSelectedIndexPath = indexPath
}
我得到的是,当 collection 视图首次启动时,它显示了我 want.But 单击照片时的行为,然后向左滚动,然后再次单击新照片,它显示错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
Optional value
我认为是之前选择的照片不再出现在屏幕上,因此无法更新该照片的 UIView 的约束。
我也尝试实现这个解决方案,但也遇到了同样的错误:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! photoCell
cell.uiViewHeight.constant = 250
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! photoCell
cell.uiViewHeight.constant = 0
}
那么在这种情况下,我该如何解决这个问题呢?
Ken,不要强制转换 UICollectionViewCell
,您的应用可能会崩溃。
使用这样的安全代码:
if let currentCell = collectionView.cellForItem(at: indexPath) as? photoCell {
// if succeed, do code
}
我有一个横向 collection view.When 用户点击一张照片,一个 UIView 似乎覆盖了 photo.Only 1 照片将可以在 1 time.Means 中选择,如果选择了一张照片,如果我点击另一张照片,前一张照片将恢复正常。
我在下面实现了这段代码:
var previousSelectedIndexPath : IndexPath?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if previousSelectedIndexPath != nil {
let previousCell = collectionView.cellForItem(at: previousSelectedIndexPath!) as! photoCell
previousCell.uiViewHeight.constant = 0
}
let currentCell = collectionView.cellForItem(at: indexPath) as! photoCell
currentCell.uiViewHeight.constant = 250
previousSelectedIndexPath = indexPath
}
我得到的是,当 collection 视图首次启动时,它显示了我 want.But 单击照片时的行为,然后向左滚动,然后再次单击新照片,它显示错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
我认为是之前选择的照片不再出现在屏幕上,因此无法更新该照片的 UIView 的约束。
我也尝试实现这个解决方案,但也遇到了同样的错误:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! photoCell
cell.uiViewHeight.constant = 250
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! photoCell
cell.uiViewHeight.constant = 0
}
那么在这种情况下,我该如何解决这个问题呢?
Ken,不要强制转换 UICollectionViewCell
,您的应用可能会崩溃。
使用这样的安全代码:
if let currentCell = collectionView.cellForItem(at: indexPath) as? photoCell {
// if succeed, do code
}