您好,我正在尝试以编程方式创建一个 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
最佳答案
您没有使用您的 CustomCollectionViewController,您使用的是 UICollectionViewController。
替换
let customCollectionViewController = UICollectionViewController(collectionViewLayout: flowLayout)
与
let customCollectionViewController = CustomCollectionViewController(collectionViewLayout: flowLayout)
您在单元格中的约束代码也导致我崩溃,但如果您只是评论这些行,您应该会看到 Collection View 出现。
关于ios - CollectionView 显示黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343830/