我可能继承我的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项目? –
我编辑了我的答案,并添加了一个简单的例子。 –