【发布时间】:2019-06-26 08:12:45
【问题描述】:
我正在尝试重新创建 iOS Gallery 应用程序,其中用户有两个集合视图控制器,第一个显示所有可用图像,第二个在用户点击图像(单元格)时显示,并且相同图像显示在另一个集合视图控制器中,具有以下功能:
DispatchQueue.main.async {
self.collectionView?.scrollToItem(at: self.customIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: false)
}
}
当用户在上一个集合视图控制器中选择一个项目时设置自定义 indexPath 的位置。
问题是,在第二个集合视图控制器(图像单独显示的地方)中,我不知道如何制作,所以当用户向右或向左滑动时,下一个/上一个图像会显示并居中,就像在该图像上调用了上述函数一样。
我尝试在下面的代码中调用上面的函数
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let newIndexPath = IndexPath(item: indexPath.item, section: 0)
print("Item at \(indexPath.item)")
self.collectionView?.scrollToItem(at: newIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
}
但是它调用得太快了,只要用户开始向前或向后收集视图,图像就会被下一张图像替换,我希望下一张图像在用户滑动或至少移动时显示并居中水平方向,上一个图像的一半以上不显示,下一个图像的一半以上显示,用户释放并自动将下一个图像居中
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var customIndexPath = IndexPath()
let images:[UIImage] = [
UIImage(named: "image_1")!,
UIImage(named: "image_2")!,
UIImage(named: "image_3")!,
UIImage(named: "image_4")!,
UIImage(named: "image_5")!,
UIImage(named: "image_6")!,
UIImage(named: "image_7")!,
UIImage(named: "image_8")!,
]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(customIndexPath)
DispatchQueue.main.async {
self.collectionView?.scrollToItem(at: self.customIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: false)
}
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.userImageView.image = images[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let newIndexPath = IndexPath(item: indexPath.item, section: 0)
print("Item at \(indexPath.item)")
self.collectionView?.scrollToItem(at: newIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
}
}
结果应该在一个非常基本的级别上非常类似于 iOS 画廊应用程序,当用户滑动时,下一个图像必须显示并居中,而不是像现在一样浮动或部分显示,如果用户滑动也是如此慢慢地并且下一个单元格(下一个图像)至少有一半的内容没有显示,那么集合视图必须显示并居中上一个图像,就像 iOS 画廊应用程序一样
到目前为止,我的项目可以在以下链接中找到:
https://github.com/francisc112/Gallery-Test
在此先感谢,如果有任何教程可以让我学习这样做,请指出。
【问题讨论】:
标签: ios swift xcode uicollectionview