要创建居中单元格被选中的UICollectionView,可以按照以下步骤进行操作:
scrollDirection
设置为.horizontal
或.vertical
,以决定滚动方向。collectionView(_:didSelectItemAt:)
方法,该方法会在用户选中某个单元格时被调用。collectionView(_:didSelectItemAt:)
方法中,获取被选中的单元格的索引路径,并调用scrollToItem(at:at:animated:)
方法将该单元格滚动到可见区域。collectionView(_:layout:insetForSectionAt:)
方法,该方法用于设置每个section的内边距。collectionView(_:layout:insetForSectionAt:)
方法中,计算每个section的左右内边距,使得单元格在水平方向上居中。下面是一个示例代码:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .white
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// MARK: - UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = .blue
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let cellWidth: CGFloat = 100 // 单元格宽度
let cellCount = CGFloat(collectionView.numberOfItems(inSection: section))
let collectionViewWidth = collectionView.bounds.width
let totalCellWidth = cellWidth * cellCount
let totalSpacingWidth = cellWidth * (cellCount - 1)
let leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
let rightInset = leftInset
return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}
}
这样,当用户选中某个单元格时,该单元格会居中显示在UICollectionView中。你可以根据实际需求进行调整和修改。
领取专属 10元无门槛券
手把手带您无忧上云