【发布时间】:2018-11-23 23:13:29
【问题描述】:
我正在尝试创建一个 3 列的 UICollectionView/网格视图,但尽管我尝试了一切,但我没有成功。
我使用的代码如下:
import UIKit
class SearchResultsViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// Actual code
@IBOutlet weak var collectionView: UICollectionView!
public var results: [UIImage]!
func loadImages(images: [UIImage]) {
results = images
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
self.navigationController?.setNavigationBarHidden(false, animated: true)
// Disable the margins
let flow = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
collectionView.contentOffset = CGPoint.zero
flow.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
flow.minimumInteritemSpacing = 0
flow.minimumLineSpacing = 0
}
// UICollectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 64
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenWidth = UIScreen.main.bounds.width
return CGSize(width: screenWidth/3, height: screenWidth/3)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 5, right: 5)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
}
我正在寻找与 Instagram 等照片应用程序类似的三列布局(请注意,64 是作为虚拟数据存在的,因此我可以测试它是否有效,如果有效,它将被实际图像替换)
我最终没有得到预期的结果,而是这样: [
【问题讨论】:
-
为什么要添加 5 的右插图?您添加的每个额外空间都必须从您的项目宽度计算中删除,在您的情况下为 (screenWidth - 5) / 3。
标签: ios swift uicollectionview autolayout