[英]UIcollectionview cell issue Swift
我有一个简单的collectionview控制器,如下所示:
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
协议。 并实现为每个集合视图单元格设置大小的方法,如下所示:
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)
}
}
它有硬编码值,但你应该明白这个想法。 集合视图宽度应该是每个项目的最大大小,因此它们不会超出框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.