【发布时间】:2018-01-30 01:46:07
【问题描述】:
在我尝试构建的应用程序中,我需要大量 UICollectionViews(大约 10 个)。我决定在不使用 Storyboards 的情况下制作 collectionViews(即完全在代码中)。 故事板使事情复杂化(对于许多 collectionViews)。
代码如下:
我)
override func viewDidLoad() {
super.viewDidLoad()
//Create the collection View
let frame = CGRect(origin: CGPoint.zero , size: CGSize(width: self.view.frame.width , height: 50))
let layout = UICollectionViewFlowLayout()
collectionView1 = UICollectionView(frame: frame, collectionViewLayout: layout)
collectionView1.dataSource = self
collectionView1.delegate = self
collectionView1.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
collectionView1.backgroundColor = UIColor.red
view.addSubview(collectionView1) }
二)
// TheData Source and Delegate
extension ViewController : UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
cell.backgroundColor = UIColor.darkGray
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 50, height: 50)
}
}
这将在 View Controller 中创建一个 collectionView,但是如果我必须再创建十个这样,我将不得不重写上述代码 10 次。
所以我尝试创建一个单独的MyCollectionView 类,其中包含将collectionView 添加到ViewController 所需的基本实现,以便
我在视图控制器中所要做的就是像
override func viewDidLoad() {
super.viewDidLoad()
let shoesCollection = MYCollectionView(frame : ...)
self.view.addSubview(shoesCollection)
let foodCollection = MYCollectionView(frame : ...)
self.view.addSubview(foodCollection)
let carCollection = MYCollectionView(frame : ...)
self.view.addSubview(carCollection)
}
或类似的东西。然而我没有成功。 我该怎么办?谢谢!
【问题讨论】:
-
子类 ViewController 具有集合视图。
-
我可以再详细一点,我不知道它是如何工作的。
-
您应该继承 ViewController,而不是将 MYCollectionView 添加到每个视图控制器。假设使用相同集合视图的其他视图控制器之一,您应该像 MySecondViewController 类一样子类化:ViewController。那么你唯一需要改变的就是覆盖 UICollectionViewDataSource 和 UICollectionViewDelegate 来显示不同的内容。
-
很抱歉我的问题有点不清楚。我需要将许多
collectionViews添加到同一个视图控制器中。我希望能够分别配置每个视图控制器,以便它显示不同的内容。但是对于我添加的所有collectionViews,基本实现仍然是相同的。我更新了问题的最后一个代码块。 -
知道了。现在这取决于您的集合视图在视图控制器中的显示方式。如果集合视图就像一行,那么您可能希望创建一个集合视图,其中包含您在其中创建的集合视图的集合视图单元格。
标签: ios swift uicollectionview reusability