簡體   English   中英

UICollectionview委托和數據源未開始調用

[英]UICollectionview Delegate and datasource not begin called

我正在嘗試以編程方式創建UICollectionview,

但是由於某種原因,未開始調用委托方法。 我可以在視圖調試器中看到委托和數據源為零,這可能是什么問題? 謝謝

在此處輸入圖片說明

    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()


    }
} 

在您的視圖控制器代碼中:

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()

    }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM