首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Swift 4中的UICollectionViewController未调用cellForItemAt函数

Swift 4中的UICollectionViewController未调用cellForItemAt函数
EN

Stack Overflow用户
提问于 2018-08-19 03:17:55
回答 1查看 675关注 0票数 2

这看起来很简单,但我不能让它在Swift 4中工作。

因此,我有以下UICollectionViewController实现

代码语言:javascript
复制
class TestController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(MyCell.self, forCellWithReuseIdentifier: "default")
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath)
    }

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


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: view.frame.width, height: 100)
    }
}

尽管正在调用... numberOfItems ...方法,但用于... cellForItemAt indexPath ...的方法尚未调用。

我遗漏了什么?

这是单元格的代码

代码语言:javascript
复制
class MyCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .green
    }

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

另外,我没有使用故事板,所以我在AppDelegate类中实例化这个控制器,如下所示:

代码语言:javascript
复制
...
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        window = UIWindow()
        window?.makeKeyAndVisible()

        window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))

        return true
    }
...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-19 04:55:15

而不是

代码语言:javascript
复制
window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))

在didFinishLaunchingWithOptions方法中使用以下代码

代码语言:javascript
复制
 window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: UICollectionViewFlowLayout()))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51911833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档