iphone 5 时 CollectionViewCell 超出屏幕
CollectionViewCell out of screen on iphone 5
我有这个自定义的 UICollectionViewCell,它在 iphone 7 上运行良好,但是当我在 Iphone 5 模拟器上 运行 它时,事情变得很奇怪。
我的 collection 视图有很多部分,每个部分一个项目。它看起来像一个 table 视图,这意味着每个单元格都是全宽的,并且它们都在彼此上方,就像在 table 视图中一样。
由于某种原因,在 Iphone 5 中,框架是:(-27.5, 50.0, 320.0, 45.7143)
这意味着它的宽度和高度正确,但它从屏幕左侧 27.5 点开始。我这样更新单元格:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> ProfileCollectionCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ProfileCollectionCell
let width = CGFloat((self.collectionView?.frame.width)!)
let height = width/7
cell.frame.size = CGSize(width: width, height: height)
return cell
}
如何才能正确定位框架?
您不应在 cellForItemAtIndexPath
中设置单元格的框架
相反,实施 UICollectionViewDelegateFlowLayout
方法…
func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) {
let width = collectionView?.frame.width ?? 0
let height = width / 7
return CGSize(width: width, height: height)
}
首先将协议添加到您的 class UICollectionViewDelegateFlowLayout
并添加以下代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let width = CGFloat((self.collectionView?.frame.width)!)
let height = width/7
return CGSize(width: width, height: height)
}
我有这个自定义的 UICollectionViewCell,它在 iphone 7 上运行良好,但是当我在 Iphone 5 模拟器上 运行 它时,事情变得很奇怪。 我的 collection 视图有很多部分,每个部分一个项目。它看起来像一个 table 视图,这意味着每个单元格都是全宽的,并且它们都在彼此上方,就像在 table 视图中一样。 由于某种原因,在 Iphone 5 中,框架是:(-27.5, 50.0, 320.0, 45.7143) 这意味着它的宽度和高度正确,但它从屏幕左侧 27.5 点开始。我这样更新单元格:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> ProfileCollectionCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ProfileCollectionCell
let width = CGFloat((self.collectionView?.frame.width)!)
let height = width/7
cell.frame.size = CGSize(width: width, height: height)
return cell
}
如何才能正确定位框架?
您不应在 cellForItemAtIndexPath
相反,实施 UICollectionViewDelegateFlowLayout
方法…
func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) {
let width = collectionView?.frame.width ?? 0
let height = width / 7
return CGSize(width: width, height: height)
}
首先将协议添加到您的 class UICollectionViewDelegateFlowLayout
并添加以下代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let width = CGFloat((self.collectionView?.frame.width)!)
let height = width/7
return CGSize(width: width, height: height)
}