ios - UICollectionView 中 80% 屏幕和 20% 屏幕的计算

标签 ios swift uicollectionview size cgsize

我编写了返回 UICollectionView 单元格大小的函数。

   fileprivate func getCellSize(with row: Int) -> CGSize {

        let percentage: CGFloat = row == 0 ? 0.8 : 0.2
        let width = self.collectionView?.frame.width
        let height = self.collectionView?.frame.height

        let expectedWidth = width! * percentage
        let expectedHeight = height! * 0.5

        return CGSize(width: expectedWidth, height: expectedHeight)
    }

这个函数工作正常,但它有一个小问题,与我认为的四舍五入有关。因为我收到的布局没有像预期的那样完全被单元格覆盖。

iPhone 6 模拟器的函数结果如下:

0:ROW = (533.60000000000002,187.5)

1:ROW = (133.40000000000001,187.5)

实际结果:

enter image description here

预期结果:

enter image description here

最佳答案

怎么样

if let frameWidth = self.collectionView?.frame.width {
     let row0Width = Int(Double(frameWidth) * 0.8)
     let otherWidth = frameWidth - row0Width
     let expectedWidth = row == 0 ? row0Width : otherWidth
     // ...
}

避免舍入问题?

关于ios - UICollectionView 中 80% 屏幕和 20% 屏幕的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43909928/

相关文章:

swift - 在 ios Swift 中的 Images.xcassets 文件夹中的 Collection View 中显示图像

ios - 如何在 iOS 7 上的三个 ViewController 之间使用 Core Data 传递数据

ios - 扩展 JSONDecoder 以允许基于端点以不同方式序列化模型

ios - swift: fatal error :在展开可选值 (lldb) 时意外发现 nil,线程 1

swift - 如何通过 CoreData 中的关系传递谓词

ios - 我需要调用 UICollectionView 的 dequeueCell : from within the data source's cellForPath:?

ios - 上下文菜单选择颜色和框架大小 Swift 5 iOS 13

objective-c - 理解和编写单例类而不是使用委托(delegate)类

ios - 我应该如何保存警报应用数据?

Swift RestKit Post 不包括发布数据