2
UICollectionView的標題顯示不正確。我在頭文件中添加了一個UILabel,它應該顯示節號。當我調試viewForSupplementaryElementOfKind時,一切看起來都不錯。我查看了關於collectionView標題的不同教程,並且在代碼中找不到該錯誤。 Swift UICollectionView標題顯示不正確
這裏是整個代碼:
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;
}
}
這不是你的問題的根源,但它很重要:你並沒有意識到'collectionView.dequeueReusableSupplementaryViewOfKind'返回一個_reusable_視圖。這個詞很重要。該視圖可能與已用於其他標題的視圖相同。如果是這樣,你不想再次添加標籤。 – matt