我想在Swift中僅使用代碼製作UICollectionView。我刪除了Main.story並完成了所有設置。它運行良好,但單元格從不顯示。我在YouTube上跟着一個教程,我發誓我的代碼是完全一樣的(除了變量名或其他),但它永遠不會顯示單元格。如果任何人都能弄清楚爲什麼,我將不勝感激。這是ViewController文件,在底部添加了AppDelegate文件。我可以更改整個控制器的背景,但更改單元格背景顏色不會執行任何操作。在Swift代碼中的UICollectionView?爲什麼我的代碼不能工作?
import UIKit
class CustomCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let customCellIdentifier = "customCellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .greenColor()
collectionView?.registerClass(CustomCell.self, forCellWithReuseIdentifier: customCellIdentifier)
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let customCell = collectionView.dequeueReusableCellWithReuseIdentifier(customCellIdentifier, forIndexPath: indexPath)
return customCell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(view.frame.width, 100)
}
}
class CustomCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Custom Text"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupViews() {
backgroundColor = UIColor.redColor()
addSubview(nameLabel)
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
let flowLayout = UICollectionViewLayout()
let customCollectionViewController = CustomCollectionViewController(collectionViewLayout: flowLayout)
window?.rootViewController = UINavigationController(rootViewController: customCollectionViewController)
// Override point for customization after application launch.
return true
}