私はSwiftでコードを使用してUICollectionViewを作成しようとしています。私はMain.storyを削除し、すべてのセットアップを完了しました。それは正常に動作しますが、セルは表示されません。私はYouTubeのチュートリアルに続き、私のコードはまったく同じであることを誓っています(変数名などを除いて)が、セルを表示することはありません。誰かが理由を理解できれば、私はそれを高く評価します。これはViewControllerファイルで、下部にAppDelegateファイルを追加しました。私はコントローラ全体の背景を変更することができますが、セルの背景色を変更することは何もしません。スイフトコードのUICollectionView?なぜ私のコードは動作しませんか?
iOS documentation hereから撮影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
}