Skip to content

Commit ec1f30d

Browse files
committed
use list cell as header, as advised by Apple
1 parent 1978c57 commit ec1f30d

File tree

1 file changed

+7
-15
lines changed

1 file changed

+7
-15
lines changed

bk2ch08p465CollectionViewLists2b/CollectionViewLists/CollectionViewController.swift

+7-15
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class CollectionViewController: UICollectionViewController {
2121
let layout = UICollectionViewCompositionalLayout.list(using: config)
2222
self.collectionView.collectionViewLayout = layout
2323
self.collectionView.register(UICollectionViewListCell.self, forCellWithReuseIdentifier: self.cellId)
24-
self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: self.headerId)
24+
self.collectionView.register(UICollectionViewListCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: self.headerId)
2525
}
2626

2727
let data = ["Manny", "Moe", "Jack"]
@@ -50,21 +50,13 @@ class CollectionViewController: UICollectionViewController {
5050
}
5151
}
5252

53+
// Apple says: for the header of a collection view list, use a list cell!
5354
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
54-
let v = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.headerId, for: indexPath)
55-
var lab : UIView! = v.viewWithTag(1)
56-
if lab == nil {
57-
lab = UILabel()
58-
lab.tag = 1
59-
lab.translatesAutoresizingMaskIntoConstraints = false
60-
v.addSubview(lab)
61-
lab.topAnchor.constraint(equalTo: v.topAnchor, constant: 5).isActive = true
62-
lab.bottomAnchor.constraint(equalTo: v.bottomAnchor, constant: -5).isActive = true
63-
lab.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 15).isActive = true
64-
v.backgroundColor = .lightGray
65-
v.layer.zPosition = 1
66-
}
67-
(lab as! UILabel).text = "Pep \(indexPath.section)"
55+
let v = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.headerId, for: indexPath) as! UICollectionViewListCell
56+
var contentConfig = v.defaultContentConfiguration()
57+
contentConfig.text = "Pep \(indexPath.section)"
58+
v.contentConfiguration = contentConfig
59+
v.layer.zPosition = 1
6860
return v
6961
}
7062
}

0 commit comments

Comments
 (0)