在常规 Xcode 项目中重复使用 playground 代码

Reuse playground code in a regular Xcode project

我有一些代码可以在我的操场上创建一个 UICollectionView。该代码可以正常工作和预览。现在我正在尝试将它重用到 Xcode 项目中,我没有收到任何错误,但模拟器上的构建只是纯白色.. 什么都看不到

有人能解释一下这是什么原因吗? :)

import UIKit
//import PlaygroundSupport

class MyViewController : UIViewController {
    var myCollectionView:UICollectionView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let view = UIView()
        view.backgroundColor = .white
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 60, height: 60)
        
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

        myCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView?.backgroundColor = UIColor.white
        
        myCollectionView?.dataSource = self
        myCollectionView?.delegate = self
 
        view.addSubview(myCollectionView ?? UICollectionView())
        
        self.view = view
    }
}

extension MyViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 9 // How many cells to display
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
        myCell.backgroundColor = UIColor.blue
        return myCell
    }
}

extension MyViewController: UICollectionViewDelegate {
 
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       print("User tapped on item \(indexPath.row)")
    }
}

// Present the view controller in the Live View window
//PlaygroundPage.current.liveView = MyViewController()

您是否转到故事板,select 文档大纲中的视图控制器,并在身份检查器中将 class 名称从 UIViewController 更改为 MyViewController?如果您不进行该更改,Xcode 假定您要使用默认的 UIViewController,它是空白的。