我已经创建了一个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)
}
}
发布于 2019-08-05 22:20:46
您可以通过在标头上保留对集合视图的引用来解决这个问题。
在不保留对集合视图的引用的情况下(而不仅仅是作为子视图添加的弱视图属性),一旦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")
}
}
https://stackoverflow.com/questions/57363296
复制相似问题