我试图以编程方式创建UICollectionview,
但由于某种原因,委托方法不会被调用。 我可以在视图调试器中看到委托和数据源是nil 可能是什么问题? 感谢
mvn install
然后我从ViewController实例化 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)
}
}
:
MyClass
答案 0 :(得分:2)
在视图控制器代码中:
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let images : [UIImage] = [...]
let cv = MyClass(contentView: self.view, images: images)
cv.startAnimation()
}
}
一旦程序执行离开viewDidLoad()
,cv
就不再存在。
您希望保留该对象,因此它可以充当委托和数据源:
class SecondViewController: UIViewController {
var cv: MyClass?
override func viewDidLoad() {
super.viewDidLoad()
let images : [UIImage] = [...]
cv = MyClass(contentView: self.view, images: images)
cv.startAnimation()
}
}