我正在尝试以编程方式创建 UICollectionview,
但由于某种原因,委托(delegate)方法未开始调用。 我可以在 View 调试器中看到委托(delegate)和数据源为 nil 可能是什么问题? 谢谢
class MyClass: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var contentView : UIView
var collectionView : UICollectionView
var images = [UIImage]()
init(contentView : UIView, images : [UIImage]) {
self.contentView = contentView
self.images = images
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: contentView.frame.width, height: 700)
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: contentView.frame, collectionViewLayout: layout)
cv.backgroundColor = .clear
let nib = UINib(nibName: "MyCell", bundle: .main)
cv.register(nib, forCellWithReuseIdentifier: "MyCell")
self.collectionView = cv
super.init()
self.collectionView.delegate = self
self.collectionView.dataSource = self
contentView.addSubview(cv)
}
}
然后我从 ViewController 实例化 MyClass
:
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let images : [UIImage] = [...]
let cv = MyClass(contentView: self.view, images: images)
cv.startAnimation()
}
}
最佳答案
在您的 View Controller 代码中:
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let images : [UIImage] = [...]
let cv = MyClass(contentView: self.view, images: images)
cv.startAnimation()
}
}
一旦程序执行离开 viewDidLoad()
,cv
就不再存在。
您想保留该对象,以便它可以充当委托(delegate)和数据源:
class SecondViewController: UIViewController {
var cv: MyClass?
override func viewDidLoad() {
super.viewDidLoad()
let images : [UIImage] = [...]
cv = MyClass(contentView: self.view, images: images)
cv.startAnimation()
}
}
关于ios - UICollectionview 委托(delegate)和数据源未开始调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48232665/