【发布时间】:2017-02-09 13:01:04
【问题描述】:
我正在开发一个 iPad 应用程序,该应用程序应该显示 4 个 CollectionView 并排显示。集合视图的高度应该是屏幕的 3/4,所以布局看起来像这样:
___________________
| top content |
|-------------------|
| CV | CV | CV | CV |
|____|____|____|____|
我试图缩小所有范围并仅使用其中一个集合视图创建一个新项目,但我一直遇到同样的问题:当我点击其中一个单元格时,它们都消失了。重现:
- 使用 Swift 作为语言,使用模板“Single View Application”创建一个新项目
- 设置情节提要:
- 在情节提要中拖动一个新的集合视图控制器
- 将情节提要 ID 设置为“CollectionViewController”
- 对于单元格:将标识符设置为 MyCollectionViewCell,在单元格中拖动标签,设置约束
- 使用以下源代码创建文件:
CollectionViewCell.swift:(通过ctrl-拖动标签到源代码创建插座)
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 模拟器的截图:
我希望我没有忘记重现问题的任何内容。以防万一,我将项目上传到了我的 Dropbox。
https://dl.dropboxusercontent.com/u/607872/CollectionViewBugZip.zip
谁能告诉我我做错了什么?
【问题讨论】:
-
现在正在看 ;)
-
我刚刚注意到了其他一些事情:即使我删除了故事板中集合视图与其数据源/委托之间的连接,但仍然显示了单元格。所以肯定有一些隐含的数据源和委托,但我不知道如何/为什么。
-
自我调整大小的单元格应该如何帮助我?我错过了什么吗?
标签: ios swift uicollectionviewcell