【问题标题】:UICollectionview Delegate and datasource not begin calledUICollectionview 委托和数据源未开始调用
【发布时间】:2018-06-22 07:03:19
【问题描述】:

我正在尝试以编程方式创建 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()


    }
} 

【问题讨论】:

  • 这个类在哪里使用?为什么它扩展NSObjectcollectionView 属性声明在哪里?
  • 为什么weak这两个属性?
  • @rmaddy 嗨,我编辑了我的代码,还 MyClass 扩展了 NSObject,因为我从我的 ViewController 实例化了 MyClass 类的对象并传递了视图
  • 为什么要创建一个名为 cv 的集合视图,却将代表分配给一个名为 collectionview 的集合视图?
  • @GustavoConde 是一回事..

标签: ios swift uicollectionview


【解决方案1】:

在您的视图控制器代码中:

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

    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2020-02-26
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    相关资源
    最近更新 更多