2015-05-02 19 views

Trả lời

17

Triển khai collectionView:viewForSupplementaryElementOfKind:atIndexPath: và cung cấp UICollectionElementKindSectionHeader dequeued chứa nhãn của bạn. Nếu đây là bố cục luồng, hãy đảm bảo đặt headerReferenceSize hoặc bạn vẫn không thấy bất kỳ thứ gì.

+1

Mã ví dụ tại đây: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch08p462collectionViewFlowLayout/ch21p748collectionViewFlowLayout/ViewController.swift – matt

2

Từ câu trả lời @ david72 của

Bạn cần phải thực hiện những điều sau đây:

  1. Bật chế độ xem header/footer phần trong Storyboard.
  2. Thực hiện phương thức collectionView:viewForSupplementaryElementOfKind.

Để biết thêm chi tiết, xem here

2

Để 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

  1. Enable Section header trong UICollectionViewCell

enter image description here

  1. Thêm tệp mới thuộc loại UICollectionReusableView
  2. 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.
  3. Thêm nhãn trong phần tiêu đề của UICollectionViewCell trong storyboard
  4. Nối nhãn trong tiêu đề phần vào file UICollectionReusableView

    class SectionHeader: UICollectionReusableView { 
        @IBOutlet weak var sectionHeaderlabel: UILabel! 
    } 
    
  5. 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

Các vấn đề liên quan