在执行当前操作后,将委托设置为自己以进行收集视图

时间:2019-09-25 08:44:12

标签: ios swift uicollectionview

Main.storyboard中有2页:FirstViewControllerSecondViewController

FirstViewController中有一个按钮。这是按钮的单击范围:

let controller = SecondViewController()
present(controller, animated: true, completion: nil)

SecondViewController中有一个集合视图组件。

import UIKit

class SecondViewController: UIViewController {

@IBOutlet weak var collectionViewOutlet: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    collectionViewOutlet.delegate = self
    collectionViewOutlet.dataSource = self


    let xib = UINib(nibName: "ViewCell", bundle: nil)
    self.collectionViewOutlet.register(xib, forCellWithReuseIdentifier: "ViewCellID")

    let v0 = self.storyboard?.instantiateViewController(withIdentifier: "subView") as! SubViewController
    temp_containerViewController = v0
}
}

extension MainPageViewController: UICollectionViewDelegate, UICollectionViewDataSource,  UICollectionViewDelegateFlowLayout
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.myPageList.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionViewOutlet.dequeueReusableCell(withReuseIdentifier: "ViewCellID", for: indexPath) as! ViewCell
    let viewController = self.temp_containerViewController
    cell.contentViewOutlet = viewController?.view
    cell.contentViewOutlet.backgroundColor = .brown
    cell.lblOutlet.text = self.myPageList[indexPath.row]

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return collectionViewOutlet.frame.size
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let index = self.collectionViewOutlet.contentOffset.x / self.collectionViewOutlet.frame.size.width
    self.pageControlOutlet.currentPage = Int(index)
    self.pageControlOutlet.numberOfPages = myPageList.count
}
}

但是下面的代码给出了错误:

collectionViewOutlet.delegate = self

如何解决此问题?如上所示,我已经为集合视图组件创建了一个出口。 这是错误句子:

  

线程1:致命错误:在隐式展开一个可选值时意外发现nil

2 个答案:

答案 0 :(得分:0)

您需要加载此行

let controller = SecondViewController()

从情节提要中(为其指定标识符第二

let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Second") as! SecondViewController

因为您的网点没有XIB

答案 1 :(得分:0)

numberOfItemsInSection func

中添加条件

第1步。

if self.myPageList.count > 0 {

  return self.myPageList.count

}else {

return 0

}

步骤2。设置标识符

let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Second") as! SecondViewController

希望其帮助