【发布时间】:2020-04-11 18:51:15
【问题描述】:
我正在尝试在集合视图中呈现基本的正方形网格。我知道我想渲染的列数和行数。但是,我无法弄清楚如何以编程方式渲染正方形。
我有一个看起来像这样的视图控制器:
class BoardViewController: UIViewController {
@IBOutlet weak var board: UICollectionView!
var game = Game()
override func viewDidLoad() {
super.viewDidLoad()
board.delegate = self
// Do any additional setup after loading the view.
}
}
extension BoardViewController: UICollectionViewDelegateFlowLayout {
}
extension BoardViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return game.getColumns() * game.getRows()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
}
}
我知道我需要使用 cellForItemAt 方法来呈现自定义单元格。
我还有一个像这样的 CustomView(UIView 的子类):
import UIKit
class CustomView: UIView {
override init(frame: CGRect){
super.init(frame: frame)
self.backgroundColor = UIColor.blue
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
然后是 BoardGridCell 类:
class BoardGridCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView = CustomView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
Apple 文档说:
“要配置你的单元格的外观,在 contentView 属性中将显示数据项内容所需的视图作为子视图添加到视图中。不要直接将子视图添加到单元格本身。单元格管理多层内容,其中内容视图只是其中一个。除了内容视图之外,单元格还管理两个背景视图,以显示单元格处于其选中和未选中状态。"
但是,每当我尝试设置 contentView 属性时,我都会收到“无法分配给属性:'contentView' 是一个只能获取的属性”。
所以我的问题是 - 如何将子视图添加到 contentView 属性?
我对 Swift 很陌生,所以如果有人能为我澄清这一点,我将不胜感激。
谢谢
【问题讨论】:
-
contentView.addSubview(_instance of your view goes here_)应该会有所帮助。不要忘记为您的customView提供框架 -
使用 self.contentView.addSubView(CustomView()) 代替 self.contentView = CustomView()
-
谢谢大家,马上试试
标签: ios swift uicollectionview uikit