簡體   English   中英

如何以編程方式為iOS中的集合視圖單元格提供寬度和高度,Swift 3

[英]How to give width and height programatically for collection view cell in ios, swift 3

我試圖以編程方式給出collectionViewCell的高度和寬度。 我使用以下方法:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let viewWidth = self.deviceWidth/3 - 5
        let viewHeight = viewWidth

        return CGSize(width :100,height: 100)
    }

這沒用。 即使此方法也沒有顯示出來。 幫幫我 在Swift 3中還有其他委托方法可以通過編程方式設置單元格的寬度和高度嗎?

方法collectionView(_:layout:sizeForItemAt:)UICollectionViewDelegateFlowLayout協議的方法,因此僅設置collectionView delegatedatasource是不夠的,您需要使用自定義類實現UICollectionViewDelegateFlowLayout ,在該自定義類中,您已經添加collectionView來調用UICollectionViewDelegateFlowLayout協議的方法。 因此,實現UICollectionViewDelegateFlowLayout如下例所示:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

請確保您的類必須實現UICollectionViewDelegateFlowLayout,如下所示:

class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
    ...
}

然后在您的類中編寫此委托方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    return CGSize(width: 100, height: 100) // The size of one cell
}

希望對您有幫助...

此方法始終有效。 請首先確保不執行此方法。 如果不是,則編寫委托UICollectionViewDelegateFlowLayout如下所示:

class MyViewController: UIViewController , UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{
   :
   :
}

而且不要忘了從情節提要或通過代碼collectionView.delegate = selfcollectionView.datasource = self綁定UICollectionView的委托和數據源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM