ios - UICollectionView 中有两个自定义单元格,但第二个单元格的大小不正确

标签 ios swift

我是 iOS 开发的新手,正在尝试创建一个 PokeDex 应用程序。我的主视图 Controller 有一个 Collection View ,它返回两种类型的自定义单元格。我的第一个单元格称为选择器单元格,位于导航栏或标题栏的正下方,无论哪个术语,我希望我的第二个自定义单元格 (descriptioncell) 位于选择器单元格的正下方并占据整个屏幕。我最初将描述单元格的高度设置为 View 的高度 - 50 以考虑选择器单元格,但我看到还有一些剩余空间显示了 Collection View 的颜色。然后我决定将 descriptionview 设置为整个 view.frame 的高度,但由于某种原因仍然有空白空间。它不是很多空间,通过使 collectionview 与我的 descriptioncell 颜色相同,一切看起来都很好,但为什么会这样?

View Controller 中的代码:

import UIKit

class PokeDexController: UICollectionViewController,      UICollectionViewDelegateFlowLayout {

private let cellID = "cellID"
private let cellID2 = "cellID2"


override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "PokeDex 386"
    //collectionView?.backgroundColor = UIColor(red: 52/255.0, green: 55/255.0, blue: 64/255.0, alpha: 1.0)
    collectionView?.backgroundColor = UIColor.white

    collectionView?.register(chooserCell.self, forCellWithReuseIdentifier: cellID)
    collectionView?.register(DescriptionCell.self, forCellWithReuseIdentifier: cellID2)

}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if (indexPath.row == 0)
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! chooserCell
        return cell
    }
    else
    {
        let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: cellID2, for: indexPath) as! DescriptionCell
        return cell2
    }
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 2
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if(indexPath.row == 0)
    {
        return CGSize(width: view.frame.width, height: 50)

    }
    else
    {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }
}

how the app currently looks, empty space between two cells

谢谢

最佳答案

我会仔细检查 view.frame 以确保它符合您的预期,只是为了排除一些简单的问题。更多时候我想承认我使用了对另一个 View 的引用,该 View 的框架与我想象的不一样。

要检查的另一件事是 UICollectionView 的内容插入/间距,特别是如果您使用 Storyboard,我不知道 Storyboard是否设置了默认插入/单元格间距。如果您总是似乎在单元格的边缘周围有一些间距,那么很可能是在 UICollectionView 本身上配置了一些填充/间距。

另一个可能的罪魁祸首可能是 AutoLayout 约束,默认情况下 Storyboard附加到布局边距而不是布局边缘。边距从真正的边缘略微插入,形成一个间隙。

希望这对某些人有所帮助,或者至少让您找到正确的地方

关于ios - UICollectionView 中有两个自定义单元格,但第二个单元格的大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787267/

相关文章:

ios - swift : Play Video in Landscape Mode When Fullscreen

ios - 无法快速设置 CustomCells 的高度

ios - 使用 CoreGraphics 在 IOS 中使用交叉影线?

iphone - 我可以使用 PAN over Bluetooth 将配件连接到 iPad 吗?

ios - 如何通过点击归因链接(iOS)来检测该应用是否已启动

ios - 在ios模拟器中查看Console.log

ios - 直接从横向右转为横向左

ios - 为什么我必须将 Bundle 资源复制到主项目才能在框架中使用图像?

ios - 在 UIScrollView 中居中 UILabel

ios - 在 iPad 上锁定方向并禁用旋转