我创建了一个TableViewController并在其上制作了一个标题。我将UICollectionViewController添加到标题中。当我点击细胞时,它们消失了。有人遇到过同样的问题吗?
import UIKit
class HeaderController {
override init(frame: CGRect) {
super.init(frame: frame)
let categoryCollectionController = CategoryCollectionController(collectionViewLayout: UICollectionViewFlowLayout())
let categoryView = categoryCollectionController.view!
categoryView.translatesAutoresizingMaskIntoConstraints = false
addSubview(categoryView)
NSLayoutConstraint.activate([
categoryView.leftAnchor.constraint(equalTo: leftAnchor),
categoryView.rightAnchor.constraint(equalTo: rightAnchor),
categoryView.topAnchor.constraint(equalTo: topAnchor),
categoryView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
class CategoryCollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellID = "UID"
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .red
collectionView.register(CellCategory.self, forCellWithReuseIdentifier: cellID)
if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CellCategory
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
最佳答案
您可以通过在标题上保留对集合视图的引用来解决此问题。
如果不保留对集合视图的引用(不仅是作为子视图添加的弱视图属性),一旦init
退出范围,它将被丢弃。
例如:
class HeaderController: UIView {
let categoryCollectionController = CategoryCollectionController(collectionViewLayout: UICollectionViewFlowLayout())
override init(frame: CGRect) {
super.init(frame: frame)
let categoryView = categoryCollectionController.view!
categoryView.translatesAutoresizingMaskIntoConstraints = false
addSubview(categoryView)
NSLayoutConstraint.activate([
categoryView.leftAnchor.constraint(equalTo: leftAnchor),
categoryView.rightAnchor.constraint(equalTo: rightAnchor),
categoryView.topAnchor.constraint(equalTo: topAnchor),
categoryView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}