Ios 创建UICollectionViewController子类并添加为childviewcontroller

Ios 创建UICollectionViewController子类并添加为childviewcontroller,ios,iphone,swift,uicollectionview,Ios,Iphone,Swift,Uicollectionview,我是iOS开发新手。我想在两个具有相同UI的不同视图控制器中创建collectionView。我想只创建一个UICollectionView,并在不同的视图控制器上继续使用它,而不是创建单独的collectionView。我可以遵循的方法是创建UICollectionViewController子类,并将其作为childviewcontroller添加到我的ViewController上,但不确定这是否正确。我不知道addChildViewcontroller如何工作,以及如何在子和父ViewC

我是iOS开发新手。我想在两个具有相同UI的不同视图控制器中创建collectionView。我想只创建一个UICollectionView,并在不同的视图控制器上继续使用它,而不是创建单独的collectionView。我可以遵循的方法是创建UICollectionViewController子类,并将其作为childviewcontroller添加到我的ViewController上,但不确定这是否正确。我不知道addChildViewcontroller如何工作,以及如何在子和父ViewController之间传递数据。如果有人能帮上忙,那就太好了。如果有任何样本代码可以实现这一点,请让我知道


非常感谢您的帮助。

您可以传递同一个collection view controller实例。在视图中添加它将在第一类和第二类中出现并在视图中删除它。这是一个您可以使用的示例代码

extension UIColor {
class func randomColor() -> UIColor {
    let red = CGFloat(arc4random_uniform(255)) / 255.0
    let green = CGFloat(arc4random_uniform(255)) / 255.0
    let blue = CGFloat(arc4random_uniform(255)) / 255.0

    return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}

类MyCollectionViewController:UICollectionViewController{
let数据:[UIColor]
初始化(数据:[UIColor]){
self.data=数据
let layout=UICollectionViewFlowLayout()
layout.itemSize=CGSizeMake(100100)
layout.scrollDirection=UICollectionViewScrollDirection.Vertical
super.init(collectionViewLayout:layout)
}
重写func viewDidLoad(){
super.viewDidLoad()
collectionView?.registerClass(UICollectionViewCell.self,强制使用ReuseIdentifier:“单元格”)
}
必需的初始化?(编码器aDecoder:NSCoder){
fatalError(“初始化(编码者:)尚未实现”)
}
重写func collectionView(collectionView:UICollectionView,numberOfItemsInSection:Int)->Int{
返回数据.count
}
重写func collectionView(collectionView:UICollectionView,cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell{
let cell=collectionView.dequeueReusableCellWithReuseIdentifier(“cell”,forIndexPath:indexPath)
cell.backgroundColor=数据[indexPath.item]
返回单元
}
}
类FirstViewController:UIViewController{
惰性变量myData:[UIColor]={
var allData=[UIColor]()
对于0..<20中的i{
allData.append(UIColor.randomColor())
}
返回所有数据
}()
var collectionViewController:MyCollectionViewController!
重写func viewDidLoad(){
super.viewDidLoad()
collectionViewController=MyCollectionViewController(数据:self.myData)
让barButton=UIBarButtonItem(标题:“显示下一步”,样式:。普通,目标:自我,动作:“显示下一步:”)
navigationItem.rightBarButtonItem=barButton
}
覆盖功能视图将出现(动画:Bool){
超级。视图将显示(动画)
让collectionView=collectionViewController.view
collectionView.TranslatesAutoResizezingMaskintoConstraints=false
view.addSubview(collectionView)
addChildViewController(collectionViewController)
collectionView.topAnchor.constraintEqualToAnchor(view.topAnchor).active=true
collectionView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active=true
collectionView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active=true
collectionView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active=true
collectionViewController.didMoveToParentViewController(自)
}
覆盖功能视图将消失(动画:Bool){
super.ViewDidEnglish(动画)
collectionViewController.willMoveToParentViewController(无)
collectionViewController.view.removeFromSuperview()
collectionViewController.removeFromParentViewController()
}
func showNext(发送方:AnyObject){
设secondViewController=secondViewController(collectionViewController:collectionViewController)
navigationController?.pushViewController(第二个ViewController,动画:true)
}
}
类SecondViewController:UIViewController{
var collectionViewController:MyCollectionViewController!
init(collectionViewController:MyCollectionViewController){
self.collectionViewController=collectionViewController
super.init(nibName:nil,bundle:nil)
}
必需的初始化?(编码器aDecoder:NSCoder){
fatalError(“初始化(编码者:)尚未实现”)
}
覆盖功能视图将出现(动画:Bool){
超级。视图将显示(动画)
让collectionView=collectionViewController.view
view.addSubview(collectionView)
collectionView.TranslatesAutoResizezingMaskintoConstraints=false
addChildViewController(collectionViewController)
collectionView.topAnchor.constraintEqualToAnchor(view.topAnchor).active=true
collectionView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active=true
collectionView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active=true
collectionView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active=true
collectionViewController.didMoveToParentViewController(自)
}
覆盖功能视图将消失(动画:Bool){
super.ViewDidEnglish(动画)
collectionViewController.willMoveToParentViewController(无)
collectionViewController.view.removeFromSuperview()
collectionViewController.removeFromParentViewController()
}
}

我有一套答案,你可以使用

  • 我的源代码是ParentViewController和ChildViewController 要声明的viewController相同

  • 首先创建ParentViewController并添加
    UICollectionView然后在ParentViewController中设置单元格大小

  • 然后在同一个parentViewController中创建UICollectionViewCell, 然后添加需要声明的标签或按钮

  • 在ParentViewController类中声明“UICollectionViewDelegate”

class MyCollectionViewController: UICollectionViewController {

    let  data: [UIColor]

    init(data: [UIColor]) {
        self.data = data
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(100, 100)
        layout.scrollDirection = UICollectionViewScrollDirection.Vertical

        super.init(collectionViewLayout: layout)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
        cell.backgroundColor = data[indexPath.item]
        return cell
    }
}


class FirstViewController: UIViewController {

    lazy var myData:[UIColor] = {
        var allData = [UIColor]()
        for i in 0 ..< 20 {
            allData.append(UIColor.randomColor())
        }
        return allData
    }()

    var collectionViewController: MyCollectionViewController!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionViewController = MyCollectionViewController(data: self.myData)

        let barButton = UIBarButtonItem(title: "Show next", style: .Plain, target: self, action: "showNext:")
        navigationItem.rightBarButtonItem = barButton
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        let collectionView = collectionViewController.view
        collectionView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(collectionView)
        addChildViewController(collectionViewController)

        collectionView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
        collectionView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
        collectionView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
        collectionView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true

        collectionViewController.didMoveToParentViewController(self)
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)

        collectionViewController.willMoveToParentViewController(nil)
        collectionViewController.view.removeFromSuperview()
        collectionViewController.removeFromParentViewController()
    }

    func showNext(sender: AnyObject) {
        let secondViewController = SecondViewController(collectionViewController: collectionViewController)
        navigationController?.pushViewController(secondViewController, animated: true)
    }
}

class SecondViewController: UIViewController {

    var collectionViewController: MyCollectionViewController!

    init(collectionViewController: MyCollectionViewController) {
        self.collectionViewController = collectionViewController
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        let collectionView = collectionViewController.view

        view.addSubview(collectionView)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        addChildViewController(collectionViewController)

        collectionView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
        collectionView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
        collectionView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
        collectionView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true

        collectionViewController.didMoveToParentViewController(self)
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)

        collectionViewController.willMoveToParentViewController(nil)
        collectionViewController.view.removeFromSuperview()
        collectionViewController.removeFromParentViewController()
    }
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return arrayvalue.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {


    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseIdentifier", forIndexPath: indexPath)

    // Configure the cell

    let baseView = cell.viewWithTag(101)
    let titleLabel = baseView?.viewWithTag(102) as! UILabel

    titleLabel.text = arrayvalue[indexPath.row] as String

    return cell
}

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

     return CGSizeMake(CellSize)
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    collectionView.deselectItemAtIndexPath(indexPath, animated:true)

    let storyBoard = UIStoryboard(name: "storyboardName", bundle: nil)
    let name: classname = storyBoard.instantiateViewControllerWithIdentifier("reuseIdentifier") as! AnotherViewController

    self.navigationController?.pushViewController(name, animated: true)
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseIdentifier", forIndexPath: indexPath)