在单独的UICollection类中使用未解析的标识符'UICollection'

问题描述 投票:1回答:2

我将在顶层菜单视图中上课。

这里是代码:

import UIKit

class TopHomeMenuBar: UIView {

let collectionView: UICollectionView = {

    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    return cv
}()

override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(collectionView)

    backgroundColor = UIColor.systemGreen
}

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

但是,我不断收到错误消息:

使用未解析的标识符'UICollection'

错误在此行代码中突出显示了UICollectionView:

    let collectionView: UICollectionView = {
ios swift xcode uicollectionview
2个回答
1
投票

确实有效

现在仅用XCODE创建了一个简单的SinlgerView项目我放了Controler(仅用于测试。通常,视图具有自己的文件。)

//
//  ViewController.swift
//
//  Created by ing.conti on 11/06/2020.
//  Copyright © 2020 ing.conti. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}


class TopHomeMenuBar: UIView {

    let collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        return cv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(collectionView)

        backgroundColor = UIColor.systemGreen
    }

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

0
投票

尝试这种方式。

private var collectionLayout = UICollectionViewFlowLayout()

lazy var collectionView: UICollectionView = {
    UICollectionView(frame: .zero, collectionViewLayout: collectionLayout)
}()

然后在layoutSubviews中根据需要设置流布局。

override func layoutSubviews() {
    super.layoutSubviews()

    collectionLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    collectionLayout.minimumLineSpacing = 0
    collectionLayout.itemSize = CGSize(width: (frame.width - 20) / 5, height: frame.height - 24)
    collectionLayout.scrollDirection = .horizontal
}
© www.soinside.com 2019 - 2024. All rights reserved.