[英]How to fetch the width and height of a programatically added view in Swift/ iOS?
[英]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
delegate
和datasource
是不夠的,您需要使用自定義類實現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 = self
和collectionView.datasource = self
綁定UICollectionView的委托和數據源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.