我有一个像这样的简单 collectionview Controller :
class ViewController1: UICollectionViewController{
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "P", for: indexPath)
return cell
}
}
单元格中只有一个 uiimageview,它有以下限制:
我的问题是:
当我在 iPhone 6 模拟器上执行这段代码时,我得到了这个(正确的方式):
但是当我在 iPhone 5 模拟器上执行这段代码时,我得到了这个(错误的方式: ImageView 在左侧屏幕之前开始并且宽度和高度相对于约束是错误的):
我正在为这个问题发疯,但我无法解决。 你能帮帮我吗?
最佳答案
您需要扩展您的 ViewController1
以符合 UICollectionViewDelegateFlowLayout
协议(protocol)。并实现为每个 Collection View 单元格设置大小的方法,如下所示:
class ViewController1: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(self.collectionView!.frame)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "P", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.collectionView!.frame.size.width, height: 120.0)
}
}
它具有硬编码值,但您应该明白了。 Collection View 宽度应该是每个项目的最大尺寸,这样它们就不会超出框。
关于ios - UIcollectionview 单元格问题 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212217/