【问题标题】:Resizing CollectionViewCell in UIView在 UIView 中调整 CollectionViewCell 的大小
【发布时间】:2016-11-07 13:25:55
【问题描述】:

我在 UIView 中有 CollectionView。如何将 CollectionViewCell 调整为屏幕宽度的 50%?我想在 CollectionView 中创建 2 列。

class Class_MyUIViewClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate 
{

我在 CollectionViewCell 中也有图像和标签。

【问题讨论】:

    标签: ios iphone swift xcode swift3


    【解决方案1】:

    您可以使用 UICollectionView 的sizeForItemAt 方法来管理它的单元格大小

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let screenWidth = UIScreen.main.fixedCoordinateSpace.bounds.width
        return CGSize(width: screenWidth/2, height: yourHeight)
    } 
    

    也确认UICollectionViewDelegateFlowLayout

    【讨论】:

    • myfile.swift:49:10: 实例方法 'collectionView(collectionView:layout:sizeForItemAtIndexPath:)' 几乎匹配协议 'UICollectionViewDelegate 的可选要求'collectionView(_:willDisplaySupplementaryView:forElementKind:at:)' '
    • 'CGSizeMake' 在 Swift 中不可用
    【解决方案2】:

    假设您知道所需的单元格高度,请遵循UICollectionViewDelegateFlowLayout

    class Class_MyUIViewClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    

    并实现sizeForItemAtIndexPath:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let desirednumberOfCollumns: CGFloat = 2
        let width = collectionView.frame.width / desirednumberOfCollumns
        return CGSize(width, yourHeight)
    }
    

    【讨论】:

    • 'CGSizeMake' 在 Swift 中不可用 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2016-07-15
    • 2013-07-16
    相关资源
    最近更新 更多