我正在开发一款iPad应用程序,该应用程序应该在屏幕上显示4个并列的CollectionView。CollectionView的高度应为屏幕高度的3/4,因此布局将类似于以下内容:
___________________
| top content |
|-------------------|
| CV | CV | CV | CV |
|____|____|____|____|
我试图将所有东西缩小,并创建一个新项目,仅包含其中一种集合视图,但我始终遇到同样的问题:当我点击其中一个单元格时,所有单元格都消失了。重现方法如下:
- 使用Swift作为语言,创建模板为“Single View Application”的新项目
- 设置Storyboard:
- 在Storyboard中拖入一个新的CollectionView Controller
- 将Storyboard ID设置为“CollectionViewController”
- 对于单元格:将标识符设为MyCollectionViewCell,在单元格中拖动标签并设置约束
- 创建具有以下源代码的文件:
CollectionViewCell.swift:(通过Ctrl-Drag标签到源代码来创建outlet)
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
CollectionViewController.swift:(注意viewDidLoad实现中的注释)
import UIKit
private let reuseIdentifier = "MyCollectionViewCell"
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
// this has to be removed to work with a custom cell class
// self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
cell.label.text = "\(indexPath.section)-\(indexPath.row)"
return cell
}
}
更改ViewController.swift的实现:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let frame = view.frame
let vc = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "CollectionViewController")
vc.view.frame = CGRect(x: 0.0, y: frame.size.height * 0.25, width: frame.size.width, height: frame.size.height * 0.75)
self.view.addSubview(vc.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这是iOS模拟器的截图: https://youtu.be/VVBsTnYLGM4 我希望我没有忘记任何重要信息以复制这个问题。 以防万一,我把项目上传到了我的dropbox。 https://dl.dropboxusercontent.com/u/607872/CollectionViewBugZip.zip 请问有人能告诉我我做错了什么吗?