我可能繼承我的UICollectionViewCell,定義所有必需的佈局類型枚舉並將其作爲參數傳遞給自定義方法中的cellForItemAtIndexPath,因此自定義集合視圖單元格知道如何佈局自身。
事情是這樣的:
enum MyLayoutType
{
case layoutA
case layoutB
case layoutC
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource
{
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: Collection View DataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCustomCVCell", for: indexPath) as! MyCustomCVCell
// Decide here what layout type you would like to set
cell.setUpWithType(layoutType: .layoutA)
return cell
}
}
,然後在您的自定義集合視圖細胞亞類(不要忘了指定自定義類在你的界面生成器文件):
class MyCustomCVCell: UICollectionViewCell
{
func setUpWithType(layoutType: MyLayoutType)
{
switch layoutType
{
case .layoutA:
self.backgroundColor = .red
case .layoutB:
self.backgroundColor = .yellow
case .layoutC:
self.backgroundColor = .blue
}
}
}
你能不能請張貼一些代碼或它的github項目? –
我編輯了我的答案,並添加了一個簡單的例子。 –