Swift: UICollectionView 以编程方式作为子类进入 UIViewController

Swift: UICollectionView into UIViewController programmatically as subclass

我有一个简单的 UIViewController,我想以编程方式将多个 UICollectionView(不止一个)放入 UIViewController

我知道这是完全可能的,但我想在子类中配置和实现 UICollectionView

问题是:

P.S。我不使用 Storyboard 或 Nib,我想 100% 以编程方式完成此操作。

提前致谢

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 90, height: 120)

    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    collectionView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(collectionView)
}

它以编程方式创建一个 UICollectionView。要添加多个集合视图,请在 .tag

的帮助下识别它们

它应该是这样的:

let controller = <your UICollectionViewController initialization>
addChildViewController(controller)
controller.view.frame = CGRectMake(...) //frame of UICollectionView you want it takes in main View
view.addSubview(controller.view)
controller.didMoveToParentViewController(self)

顺便说一下,如果在 Interface Builder 中使用 "Container view" 实际上会容易得多。那么您就不必担心任何这些包含相关的调用,Interface Builder 会为您处理。