我正在尝试在视图控制器中使用两个集合视图,因此我收到此错误消息?你能指出我错过了什么来纠正这个问题吗?提前致谢.. 下面是名为" OtherViewController"。
的视图控制器中的代码类OtherViewController:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
//1. CREATE A VARIABLE FOR YELLOW ARRAY SO THAT I CAN DEFINE A STRING
var exploreArray = [String]()
var exploreHeader = [String]()
var yellowImages = [String]()
var explorecategories = [String]()
@IBOutlet weak var mycollectionView: UICollectionView!
var collectionViewA = UICollectionView()
let collectionViewB = UICollectionView()
let collectionViewAIdentifier = "yellowCell"
let collectionViewBIdentifier = "yellowCell2"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionViewA.delegate = self
collectionViewB.delegate = self
collectionViewA.dataSource = self
collectionViewB.dataSource = self
self.view.addSubview(collectionViewA)
self.view.addSubview(collectionViewB)
}
func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection section:Int) - > Int {
if collectionView == self.collectionViewA {
return exploreArray.count }
return 1 // Replace with count of your data for collectionViewB
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionViewA{
let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "yellowCell", for: indexPath) as! yellowCell
// Set up cell
//DISPLAY TITLE LABEL
cellA.yLabel.text = exploreHeader[indexPath.row]
//DISPLAY IMAGES
cellA.yellowImages.image = UIImage(named:yellowImages [indexPath.row])
//DISPLAY DESCRIPTION
cellA.yellowTextField.text = exploreArray [indexPath.row]
return cellA
}
else {
let cellB = collectionView.dequeueReusableCell(withReuseIdentifier: "yellowCell2", for: indexPath) as! yellowCell2
cellB.labe2.text = "Dolphin"
//只是radom标签来查看cellB是否会出现在集合视图中
return cellB
}
}
答案 0 :(得分:0)
我认为this question给出的答案也可能对您的情况有所帮助。
具体来说,你在哪里
var collectionViewA = UICollectionView()
let collectionViewB = UICollectionView()
建议(由比我更聪明的几个人)改为使用
var collectionViewA: UICollectionView!
var collectionViewB: UICollectionView!
然后在viewDidLoad()中,设置委托和dataSource(就像你一样),添加类似
的内容let layoutA = UICollectionViewFlowLayout()
layoutA.itemSize = CGSize(width: 100, height: 100)
let layoutB = UICollectionViewFlowLayout()
layoutB.itemSize = CGSize(width: 100, height: 100)
collectionViewA = UICollectionView(frame: self.view.frame, collectionViewLayout: layoutA)
collectionViewB = UICollectionView(frame: self.view.frame, collectionViewLayout: layoutB)
然后在添加子视图后最终
collectionViewLeft.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewLeftIdentifier)
collectionViewRight.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewRightIdentifier)
完整代码显示在链接问题的答案中。 (它使用左和右而不是A& B,但希望同样的想法适用。)