Để thêm nhãn tùy chỉnh trên hết mọi phần trong UICollectionView, hãy làm theo các bước dưới đây
- Enable Section header trong UICollectionViewCell
- Thêm tệp mới thuộc loại UICollectionReusableView
- Trong bảng phân cảnh thay đổi lớp tiêu đề phần trong UICollectionViewCell thành tệp mới được thêm kiểu UICollectionReusableView.
- Thêm nhãn trong phần tiêu đề của UICollectionViewCell trong storyboard
Nối nhãn trong tiêu đề phần vào file UICollectionReusableView
class SectionHeader: UICollectionReusableView {
@IBOutlet weak var sectionHeaderlabel: UILabel!
}
Trong ViewController thêm mã dưới đây
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionHeader", for: indexPath) as? SectionHeader{
sectionHeader.sectionHeaderlabel.text = "Section \(indexPath.section)"
return sectionHeader
}
return UICollectionReusableView()
}
Ở đây "SectionHeader" là tên của tệp được thêm vào để loại UICollectionReusableView
Nguồn
2017-10-20 11:13:31
Mã ví dụ tại đây: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch08p462collectionViewFlowLayout/ch21p748collectionViewFlowLayout/ViewController.swift – matt