无法使用分段控件显示UICollectionView

时间:2016-04-11 07:06:03

标签: ios swift uisegmentedcontrol

在我的主视图Controller中,我有一个分段控件和一个容器视图。我想切换分段控件时更改容器视图。当我切换选项卡时,我可以看到正在加载的视图(在viewDidload中打印),但是,我发现它不能使用collectionViewDataSource的数据源。有什么想法吗?

enter image description here

// Main View
let videoViewController = VideoViewController()
let photoViewController = PhotoViewController()


private var activeViewController: UIViewController? {
    didSet {
        removeInactiveViewController(oldValue)
        updateActiveViewController()
    }
}

@IBOutlet weak var containerView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    activeViewController = videoViewController

}

@IBAction func segmentDidChanged(sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0 {
        print("\(sender.titleForSegmentAtIndex(0)!) Selected")
        activeViewController = videoViewController

    } else if sender.selectedSegmentIndex == 1 {
        print("\(sender.titleForSegmentAtIndex(1)!) Selected")
        activeViewController = photoViewController
    }
}


private func removeInactiveViewController(inactiveViewController: UIViewController?) {
    if let inActiveVC = inactiveViewController {
        // call before removing child view controller's view from hierarchy
        inActiveVC.willMoveToParentViewController(nil)

        inActiveVC.view.removeFromSuperview()

        // call after removing child view controller's view from hierarchy
        inActiveVC.removeFromParentViewController()
    }
}

private func updateActiveViewController() {
    if let activeVC = activeViewController {
        // call before adding child view controller's view as subview
        addChildViewController(activeVC)

        activeVC.view.frame = containerView.bounds
        containerView.addSubview(activeVC.view)

        // call before adding child view controller's view as subview
        activeVC.didMoveToParentViewController(self)
    }
}

// PhotoView
@IBOutlet weak var collectionView: UICollectionView!


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    print("HI")
}
extension PhotoViewController : UICollectionViewDataSource {

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 2
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 2
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as!PhotoCollectionViewCell
    cell.backgroundColor = UIColor.blackColor()
    // Configure the cell
    cell.imgView.image = UIImage(named: "test")
    return cell
}
}

当我将PhotoViewController作为初始控制器时,它可以工作。

enter image description here

0 个答案:

没有答案