微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

重用常规Xcode项目中的Playground代码

如何解决重用常规Xcode项目中的Playground代码

我有一些代码可以在操场上创建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()

解决方法

您是否进入了情节提要,在文档大纲中选择了视图控制器,然后在Identity Inspector中将类名称从UIViewController更改为MyViewController?如果您不进行更改,则Xcode会假定您要使用默认的UIViewController,该默认值为空白。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。