嵌入在Navigation Controller中时,CollectionView不起作用

时间:2016-12-31 20:14:28

标签: uicollectionview swift3

我有一个简单的集合视图测试(基于在线教程),它可以很好地独立工作。但是当我将它嵌入导航控制器时,它就会停止工作。我在代码中构建了屏幕:(1)创建一个headerView(64像素高)并将其添加到顶部的视图中。 (2)我构建了一个集合视图并将其添加到headerView。

以下是代码:

import UIKit

class ViewController: UIViewController,
UICollectionViewDelegate, UICollectionViewDataSource,
UINavigationControllerDelegate
{
var collectionView : UICollectionView!
var topView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    var frame = CGRect(x:0,y:128, width:view.frame.width, height:64)
    topView = UIView(frame:frame)
    self.view.addSubview(topView)

    // CollectionView
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    layout.itemSize = CGSize(width: 50, height: 50)

    frame = CGRect(x: 0, y: 0, width: Int(self.topView.frame.width), height: Int(self.topView.frame.height))
    collectionView = UICollectionView (frame: frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
    collectionView.backgroundColor = UIColor.green
    self.topView.addSubview(collectionView)

}

//MARK: - CollectionView

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



func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    for v in cell.subviews {
        v.removeFromSuperview()
    }
    cell.backgroundColor = UIColor.orange

    let label = UILabel(frame: CGRect(x:0 , y:0 , width:50 , height:50))
    label.text = "\(indexPath.item)"
    label.textAlignment = .center
    label.textColor = UIColor.white
    cell.addSubview(label)

    return cell
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

1 个答案:

答案 0 :(得分:0)

我无法按照陈述的方式使考查尔的建议工作。它确实给了我一个线索,我对嵌入集合视图的视图的定位在viewDidLoad中被错放了,原因我还没理解。但是,通过将集合视图配置放在viewDidAppear(而不是viewDidLoad)中,它运行良好。我将y位置偏移64以清除导航栏,并将行高减少到64.我还将代码只执行一次,以便从页面导航不会添加多个彼此顶部的视图。顺便说一句,我最初的目标是水平滚动细胞。在我的程序中,我有相应部分的tableview,并且想法是使用具有水平滚动单元格的行移动到相应的部分。

代码如下所示:

    //
//  CustomViewController.swift
//  DSM Tracker
//
//  Created by Syed Tariq on 1/7/17.
//  Copyright © 2017 com.syedtariq. All rights reserved.
//

import UIKit


class ViewController: UIViewController,
    UICollectionViewDelegate,
    UICollectionViewDataSource,
    UINavigationControllerDelegate

{

    var executeOnce = true
    var cellDimensions = [String:Int]()
    var cellHeight = 50
    var cellWidth = 120

    var collectionContainerView: UICollectionView!
    var navBar: UINavigationBar = UINavigationBar()


    // view constants
    var viewY = CGFloat()
    var viewX = CGFloat()
    var viewWidth = CGFloat()
    var viewHeight = CGFloat()


    // gaps from view edge
    let leftGap = CGFloat(20)
    let rightGap = CGFloat(20)


    // navbar constants
    let navBarHeight = CGFloat(64)

    var headerLabels = ["Cell 01","Cell 02","Cell 03","Cell 04","Cell 05","Cell 06","Cell 07","Cell 08","Cell 09","Cell 10","Cell 11","Cell 12","Cell 13","Cell 14","Cell 15","Cell 16"]


    override func viewDidLoad() {
        super.viewDidLoad()
        navBar.backgroundColor = UIColor.green
        executeOnce = true
        viewY = view.frame.origin.y
        viewX = view.frame.origin.x
        viewWidth = view.frame.width
        viewHeight = view.frame.height
    }



    func configureCollectionView () {
        if executeOnce {
            executeOnce = false
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
            layout.itemSize = CGSize(width: cellWidth, height: cellHeight)

            let colWidth = viewWidth - leftGap - rightGap
            let colX = viewX + leftGap
            let colY = viewY + navBarHeight
            let colHeight = CGFloat(64)
            let frame = CGRect(x:colX, y:colY, width: colWidth, height: colHeight)
            //let frame = CGRect.zero
            collectionContainerView = UICollectionView (frame: frame, collectionViewLayout: layout)
            collectionContainerView.dataSource = self
            collectionContainerView.delegate = self
            collectionContainerView.autoresizingMask = [.flexibleLeftMargin,.flexibleLeftMargin,.flexibleBottomMargin,.flexibleRightMargin, .flexibleHeight, .flexibleWidth]
            collectionContainerView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
            collectionContainerView.backgroundColor = UIColor.blue
            collectionContainerView.allowsSelection = true
            collectionContainerView.isScrollEnabled = true
            collectionContainerView.setNeedsDisplay()
            print("collectionContainerView.frame \(collectionContainerView.frame)")
            view.addSubview(collectionContainerView)
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        configureCollectionView()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("headerLabels.count \(headerLabels.count)")
        return  headerLabels.count
    }



    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        for v in cell.subviews {
            v.removeFromSuperview()
        }

        let cellTitle = headerLabels[indexPath.row]
        let cellTitleLines = cellTitle.components(separatedBy: " ")
        let nLabels = cellTitleLines.count

        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8
        let labelHeight = cellHeight / cellTitleLines.count
        for i in (0 ..< nLabels) {
            let frame = CGRect(x: 0, y: labelHeight * i, width: cellWidth, height: labelHeight)
            let label1 = UILabel(frame: frame)
            cell.backgroundColor = UIColor.lightGray
            label1.numberOfLines = 1
            label1.text = headerLabels[indexPath.row]
            label1.textAlignment = .center
            label1.textColor = UIColor.black
            label1.clipsToBounds = true
            label1.adjustsFontSizeToFitWidth = true
            label1.text = cellTitleLines[i]
            cell.addSubview(label1)
        }

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        collectionContainerView.scrollToItem(at:IndexPath(item: indexPath.item, section: 0), at: .centeredHorizontally, animated: false)

        return true
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionContainerView.cellForItem(at: indexPath)
        print("cell = \(cell)")
        collectionContainerView.scrollToItem(at:IndexPath(item: indexPath.item, section: 0), at: .centeredHorizontally, animated: false)
    }


    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }


    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    }



    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    }
}