2017-06-03 136 views
0

嗨我想通過編程方式使一個collectionView。我改變了它的顏色,它仍然顯示默認的顏色。代碼並不真正起作用。我很確定它在appDelegate中的問題,但無法弄清楚。 這裏是我的appDelegate使用方法:CollectionView顯示黑色屏幕

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

+0

您確定包含該集合視圖的控制器設置爲初始視圖控制器嗎? –

回答

0

您未使用yourCustomCollectionViewController,您正在使用UICollectionViewController。

更換

let customCollectionViewController = UICollectionViewController(collectionViewLayout: flowLayout) 

與細胞

let customCollectionViewController = CustomCollectionViewController(collectionViewLayout: flowLayout) 

你的約束代碼也引起了我的崩潰,但如果你只是註釋這些行,你應該看到的CollectionView出現。