swift - Swift UICollectionview 水平单元格显示中心位置,并根据单元格选择自动移动
问题描述
我的场景,我正在UICollectionView
使用水平滚动菜单实现。在这里,我需要显示选定的单元格自动移动到中心位置。在单元格中,我有菜单标签,我正在使用storyboard
.
在我的代码下方,
extension CameraViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.reuseID, for: indexPath) as! cameraModeCollectionViewCell
cell.cameraMode.text = self.items[indexPath.item]
if selectedIndex == indexPath.row {
cell.cameraMode.textColor = colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
} else {
cell.cameraMode.textColor = colorLiteral(red: 0.8884977698, green: 0.3220310807, blue: 0, alpha: 0.7236373766)
}
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)!")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = self.items[indexPath.row]
let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
return CGSize(width: cellWidth, height: collectionView.bounds.height)
}
}
解决方案
你只需要打电话scrollToItem(at:at:animated:)
,collectionView
即
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)")
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) //here.....
}
无需打电话reloadData()
或在collectionView
.
推荐阅读
- javascript - 在 React 中动态选择一个 json 键值对
- ios - 在 UITapGestureRecognizer 操作中引用发件人
- c# - 射击。镜头与 List 集合的碰撞
- filter - 添加下拉菜单以选择滤镜散景
- r - R Session Aborted 和 R 遇到致命错误 | 工作室
- mathjax - 在 slate js 中添加内联块(数学方程)
- api - 如何预防一些方法
- java - 错误 TextView 无法转换为 android.widget.Spinner
- swift - Cocoa Swift:登录时启动不起作用并在 Xcode 中引发错误?
- jquery - 隐藏列后jQuery Datatable没有响应排序到底部