Swift 4中的UICollectionViewController不能调用cellForItemAt函数

时间:2018-08-18 19:17:55

标签: ios swift uicollectionview swift4 uicollectionviewdelegate

这看起来很基础,但是我不能在Swift 4中使用它。

所以我有以下UICollectionViewController实现

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 ...的方法。

我想念什么?

这是单元格的代码

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类中实例化此控制器,如下所示:

...
    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
    }
...

1 个答案:

答案 0 :(得分:2)

代替

*.psd1

在didFinishLaunchingWithOptions方法中使用此

window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))
相关问题