【问题标题】:CollectionView Cell dynamic height for all screensizes所有屏幕尺寸的 UICollectionViewCell 动态高度
【发布时间】:2017-07-07 12:11:02
【问题描述】:

在我的项目中,我的 collectionview 单元格包含整个屏幕的宽度和高度,我已将其设置为水平滚动并使其适用于所有屏幕尺寸,我正在使用此方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height: CGFloat = view.frame.size.height
    let width: CGFloat = view.frame.size.width

        return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)

它工作得非常好,并处理所有屏幕尺寸的宽度和高度,但问题是在滚动时它会从右边缘切割屏幕,我尝试使用不同的方法 viewDidLayoutSubViews() 的 uicollectionviewdelegateflowlayout 和它也可以处理屏幕尺寸,但仍然存在相同的问题。第一张图像是原始单元格应该如何显示。

下一张图片是它如何在滚动时切断右边缘。最初我有静态 numberofIteminSection 并在每次滑动时继续切割。这是第三次或第四次滑动的结果。我启用了分页,所以我不知道这里有什么问题。

我已经检查了有关堆栈溢出的各种帖子,但似乎没有任何帮助,我被卡住了。任何帮助将不胜感激。

【问题讨论】:

    标签: swift3 uicollectionviewcell xcode8


    【解决方案1】:

    您需要检查sizeForItemAtIndexPath中的屏幕尺寸,例如:

      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    
            let screenSize: CGRect = UIScreen.main.bounds
            let screenWidth = screenSize.width
    
            if screenWidth == 414{
                return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)
    
            }else if screenWidth == 375{
    
                return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)
            }else{
    
                return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50 )
            }
        }
    

    还可以添加这些功能并根据您的需要进行自定义:

    func collectionView(_ collectionView: UICollectionView,
                                layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
                return  UIEdgeInsetsMake( 5,  14, 5,  14)
            }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
                return 4;
            }
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
            return 4;
        }
    

    如果这不起作用,则将UIEdgeInsetsMake 更改为insetForSectionAt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      相关资源
      最近更新 更多