2

UICollectionView のヘッダーが正しく表示されません。ヘッダーに UILabel を 1 つ追加し、セクション番号を表示する必要があります。viewForSupplementaryElementOfKind をデバッグすると、すべて問題ないように見えます。collectionView ヘッダーに関するさまざまなチュートリアルを見てきましたが、コードにエラーが見つかりません。 ここに画像の説明を入力

ここにコード全体があります:

import UIKit

class ViewController: UIViewController {

    var collectionView:UICollectionView!;

    override func viewDidLoad() {
        super.viewDidLoad()

        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout();
        layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20);
        layout.itemSize = CGSize(width: 60, height: 60);
        layout.headerReferenceSize = CGSize(width: CGRectGetWidth(self.view.bounds), height: 50);

        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout);


        collectionView.dataSource = self;
        collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell");
        collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header");
        collectionView.delegate = self;
        self.view.addSubview(collectionView);

    }

}

extension ViewController:UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5;
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
       return 10
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath);

        cell.backgroundColor = UIColor.whiteColor();

        return cell;
    }




    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath)

        view.backgroundColor = UIColor.blueColor();


        let label = UILabel(frame: view.frame);
        label.text = String(indexPath.section);
        label.font = UIFont(name: "helvetica", size: 40);
        label.textAlignment = .Center;
        view.addSubview(label);



        return view;

    }


}
4

1 に答える 1

6

ラインを交換する

let label = UILabel(frame: view.frame);

let label = UILabel(frame: view.bounds);

ただし、補足ビューの再利用に関するコードの他の問題を修正する必要があることに注意してください。UICollectionReusableViewデータ ソースから新しいラベルを手動で追加するのではなく、内部にラベルを含む のサブクラスを作成することをお勧めします。

于 2015-10-15T19:44:49.873 に答える