UICollectionReusableView 메서드가 호출되지 않음


79

의 섹션에 UICollectionView이미지가있는 머리글이 있어야합니다.

나는 다음 단계를 따랐다.

  • 스토리 보드에서 헤더를 액세서리로 할당했습니다. UICollectionView
  • 식별자를 주었다
  • UICollectionReusableView그것에 대한 하위 클래스를 만들었습니다.
  • 스토리 보드의 클래스에 사용자 지정 클래스를 할당했습니다.
  • ImageView헤더 액세서리에 넣어
  • 파일 ImageView의 사용자 정의 클래스에 대한 콘센트를 만들었습니다..h
  • 에서 다음을 구현했습니다 viewDidLoad.

 

[self.collectionView registerClass:[ScheduleHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;

    if (kind == UICollectionElementKindSectionHeader)
    {
        ScheduleHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];

        headerView.headerImageView.image = [UIImage imageNamed:@"blah.png"];

        reusableview = headerView;
    }

    return reusableview;
}

모든 셀과 해당 섹션을 볼 수 있기 때문에 데이터 소스 및 대리자 메서드가 작동하고 있음을 알고 있습니다. 그러나 내 헤더가 없습니다. 위의 메서드에 중단 점을 입력했는데 호출되지 않습니다.

내가 도대체 ​​뭘 잘못하고있는 겁니까?


3
kind == UICollectionElementKindSectionHeader문자열 내용 대신 문자열 포인터를 비교하므로 대신 사용하고 싶을 [kind isEqualToString: UICollectionElementKindSectionHeader]것입니다.
Mac_Cain13 2014

답변:


200

헤더에 0이 아닌 크기를 지정해야하거나 collectionView:viewForSupplementaryElementOfKind:atIndexPath호출되지 않은 것 같습니다 . 따라서 headerReferenceSize다음과 같이 흐름 레이아웃 의 속성을 설정합니다 .

flowLayout.headerReferenceSize = CGSizeMake(self.collectionView.frame.size.width, 100.f);

Swift 5 이상

flowLayout.headerReferenceSize = CGSize(CGSize(width: self.collectionView.frame.size.width, height: 100))

또는 collectionView:layout:referenceSizeForHeaderInSection섹션별로 크기를 변경하려는 경우 구현 하십시오.


1
컬렉션 뷰에서 headerReference 크기를 정의하는 대신 자동 레이아웃으로 동적 높이를 수행 할 수 있습니까?
Khant Thu Linn

flowLayout의 Storyboard에서 headerReferenceSize를 설정할 수 있습니까?
Radek Wilczak

1
예, 작동했습니다! layout.headerReferenceSize = CGSize (width : (self.collectionView? .frame.width) !, 높이 : 50); swift4
Antony Ouseph

headerReferenceSize작동하지만 섹션마다 다른 크기가 필요합니다. 그리고 사용자가 지정한 방법은 전혀 호출되지 않습니다
Vyachaslav Gerchicov

33

당신은 질문에 대답했지만 말로 더 잘 이해합니다.

메서드를 호출하려면 다음 메서드를 추가하십시오.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(60.0f, 30.0f);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(60.0f, 30.0f);
}

... 그리고 거기에서 가십시오.


31

Swift 4 Xcode 9.1 베타 2

@objc 추가

@objc func collectionView(_ collectionView: UICollectionView, layout  collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
    let size = CGSize(width: 400, height: 50)
    return size
}

크레딧 : https://medium.com/@zonble/your-delegation-methods-might-not-be-called-in-swift-3-c6065ed7b4cd


감사합니다! 내 엉덩이를 구했습니다. Btw,이 함수가 collectionViewDelegate의 자동 완성 목록에 표시되지 않는 것으로 나타났습니다. 이유를 모르겠습니다. 너무 이상합니다. 또한 그 앞에 @objc 태그가 필요하다는 것도 이상합니다.
C0D3

3
@objc를 Swift 4의 함수에 추가하는 것만으로도 효과적이었습니다. 어리석은.
Louis Cremen

7
UICollectionViewFlowLayout을 사용하는 경우 UICollectionViewDelegate 대신 UICollectionViewDelegateFlowLayout을 준수하면 @objc 없이도 문제가 해결됩니다.
nemissm

collectionView 경계를 사용하여 섹션 머리글 / 바닥 글과 함께 설정하는 것이 훨씬 좋습니다. let size = CGSize (collectionView.bounds.width, height : 50)
omaestra

18

현재 인터페이스에 UICollectionViewDelegateFlowLayout을 추가 했습니까? 이것은 나를 위해 일했습니다.

@interface MyViewController () <UICollectionViewDelegateFlowLayout>

빠른:

class MyViewController: UICollectionViewDelegateFlowLayout {


1
아! 그래서 이것은 ... 그것을이다UICollectionViewDelegateFlowLayout
Ayan Sengupta

8

Swift 3.0 (xcode 8.2.1)

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width:collectionView.frame.size.width, height:30.0)
}

5

빠른 버전이 있습니다.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    let size = CGSize(width: 400, height: 50)
    return size
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
    let size = CGSize(width: 400, height: 50)
    return size
}

XCode (버전 7.3.1)는 자동 완성에서 이러한 메서드를 제안하지 않습니다!

헤더 만 원하는 경우 헤더 메소드를 유지하십시오.


3
    @objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:)
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { }

위의 코드는 나를 위해 일했습니다.


2

내 문제는 신속한 3에서 viewForSupplementaryElementOfKind 함수의 이름이 스택 오버플로에 있던 모든 게시물에서 약간 변경되었다는 것입니다. 따라서 그것은 결코 호출되지 않았습니다. 스위프트 3에 있다면 델리게이트 함수 일치인지 확인하십시오.

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {}

내 것도. 나를 위해 "at"대신 "_", "atIndexPath"가 누락되었으며 "IndexPath"대신 "NSIndexPath"가있었습니다. 어딘가에서 방법을 복사했고 IDE에서 오류를주지 않았습니다.
Ashkan Sarlak

1

나는 같은 문제가 있습니다. 나는 추가 referenceSizeForFooterInSection했지만 전화를 viewForSupplementaryElementOfKind받지 못했습니다. 이 코드를 추가 viewDidLoad()했으며 저에게 효과적이었습니다.

if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.sectionFootersPinToVisibleBounds = true   
}

0

나를 위해 Swift 4.2에서는 func collectionView (collectionView : kind : indexPath :)-> UICollectionReusableView가 호출되지 않았습니다. 이것은 UIViewController의 컬렉션 뷰를위한 것입니다. 기존 컬렉션 뷰 함수가 @objc로 정규화되었으며 UICollectionView가 UICollectionViewDataSource 및 UICollectionViewDelegate 프로토콜을 채택하지 않았 음을 확인했습니다. 프로토콜을 채택하자마자 컬렉션 뷰 기능이 프로토콜과 일치하지 않는다는 오류가 발생했습니다. 함수 구문을 수정하고 한정자를 제거했으며 섹션 헤더가 작동하기 시작했습니다.


0

제네릭 서브 클래스가있는 경우 ObjC 델리게이트 메서드 이름 이 Swift 이름 ( https://bugs.swift.org/browse/SR-2817 ) 과 다른 경우 신중하게 지정해야합니다 .

@objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:)
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
...
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.