CollectionView显示黑屏

时间:2017-06-03 12:16:26

标签: ios swift xcode swift3 uicollectionview

您好我正在尝试以编程方式创建collectionView。我改变了它的颜色,它仍然显示默认颜色。代码并没有真正起作用。我很确定它在appDelegate中的问题,但无法弄明白。 这是我在appDelegate中的应用程序方法:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Create one
    window = UIWindow(frame: UIScreen.main.bounds)

    //Shows the window and makes it the key window.
    window?.makeKeyAndVisible()

    //Must give a layout to it by default
    let flowLayout = UICollectionViewFlowLayout()
    let customCollectionViewController = UICollectionViewController(collectionViewLayout: flowLayout)
    window?.rootViewController = UINavigationController(rootViewController: customCollectionViewController)
    return true
}

这是CollectionViewController代码

class CustomCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

let identifier = "customCell"
override func viewDidLoad() {
    super.viewDidLoad()
    collectionView?.backgroundColor = UIColor.gray
    collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: identifier)
}


override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
    return customCell
}



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

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

}

class CustomCell: UICollectionViewCell{
   override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "Hello World"

    label.translatesAutoresizingMaskIntoConstraints = false
    return label

}()

func setupViews(){
    backgroundColor = UIColor.white
    addSubview(nameLabel)

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|v0|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|v0|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
}

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

}

我正在使用Xcode 8.2.1

1 个答案:

答案 0 :(得分:0)

你没有使用yourCustomCollectionViewController,你正在使用UICollectionViewController。

替换

    let customCollectionViewController = UICollectionViewController(collectionViewLayout: flowLayout)

    let customCollectionViewController = CustomCollectionViewController(collectionViewLayout: flowLayout)

单元格中的约束代码也会导致崩溃,但如果您只是注释这些行,则会看到集合视图出现。