使收藏视图单元格水平单元格比其他单元格大



>我有一个集合视图,想使中心单元格比其他单元格大,当移动到上一个或下一个单元格时,使其在中心更大

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionView {
return slidData.count
} else {
return categoryData.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! SliderImgCell
cell.categoryName.text = slidData[indexPath.row].imageTitle
cell.detail.text = slidData[indexPath.row].imageContent
cell.pics = slidData[indexPath.item]
return cell
} else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryName.text = categoryData[indexPath.row].depName
cell.pics = categoryData[indexPath.item]
return cell
}
}

您需要像这样保存选定的 indexPath:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPath = indexPath 
}

集合视图必须确认 UICollectionViewDelegateFlowLayout。然后在 sizeForItemAt 方法中调整单元格大小:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath == selectedIndexPath {
return CGSize(width: 200, height: 90)
} else {
return CGSize(width: 180, height: 80)
}
}

基本上你想要一个轮播动画。

看看这个库,要么使用它的全部,要么从代码中获取帮助。

您可以使用ScrollViewDidScroll(_:)方法并找到中心单元格并将其放大来实现此目的。 我在下面的代码上写了明确的注释,如果您想深入了解详细信息,请查看我关于此的文章:

https://medium.com/@sh.soheytizadeh/zoom-uicollectionview-centered-cell-swift-5-e63cad9bcd49

func setFocusedCellStyle(_ scrollView: UIScrollView) {
guard scrollView is UICollectionView else { return }
// get the centerPoint
let centerPoint = CGPoint(x: self.collectionView.frame.size.width / 2 + scrollView.contentOffset.x, y: self.collectionView.frame.size.height / 2 + scrollView.contentOffset.y)
// get the indexPath for the cell at center
if let indexPath = self.collectionView.indexPathForItem(at: centerPoint), self.centerCell == nil {
// centerCell is instance variable of type: YourCell
self.centerCell = (self.colorPickerCollectionView.cellForItem(at: indexPath) as! CustomCollectionViewCell)
UIView.animate(withDuration: 0.2) {
// Choose desired scale value
self.transform = CGAffineTransform(scaleX: 1.58, y: 1.58)
}
}
if let cell = self.centerCell { // center cell is global variable
let offsetX = centerPoint.x - cell.center.x // get to current position of the cell
// when cell is 15 pixels away from the center to the sides
// reset the cell size.
if offsetX < -15 || offsetX > 15 {
UIView.animate(withDuration: 0.2) {
self.transform = CGAffineTransform.identity
}
self.centerCell = nil // set this to nil so next cell in the center will enter the above scope
}
}
}

相关内容

最新更新