如何设置UICollectionViewDelegateFlowLayout?

Ric*_*aca 96 flowlayout ios uicollectionview

UIViewController维护对UICollectionView的引用.控制器应使用UICollectionViewDelegateFlowLayout修改内置流布局.

将视图的数据源设置为self非常容易:

MyViewController.m

- (void)viewDidLoad
{
    self.collectionView.dataSource = self;
}
Run Code Online (Sandbox Code Playgroud)

但是如何将控制器设置为视图的委托流布局?

- (void)viewDidLoad
{
    self.collectionView.dataSource= self;
    // self.collectionView.??? = self; 
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

- (void)viewDidLoad
{
    self.collectionView.dataSource= self;
    self.collectionView.collectionViewLayout = self; 
}
Run Code Online (Sandbox Code Playgroud)

但我得到错误:"不兼容的指针类型分配......".

集合头文件如下所示:

MyViewController.h

@interface MyViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
Run Code Online (Sandbox Code Playgroud)

Joh*_*pia 238

只是self.collectionView.delegate = self;.请注意,UICollectionViewDelegateFlowLayout继承自UICollectionViewDelegate.

我承认一开始它会让你措手不及.

哦,这只有在self.collectionView.collectionViewLayout实际设置为您的流程布局时才有效.(或设置initWithFrame:collectionViewLayout:)

  • 可能,`self.collectionViewLayout = UICollectionViewFlowLayout()`,`self.collectionViewLayout = [[UICollectionViewFlowLayout alloc] init]` (3认同)
  • @JohnEstropia,抱歉,问题,但如何在代码中初始化自定义布局?我看到了带有故事板的示例,但没有看到代码本身。我该怎么办? (2认同)

WIN*_*gey 12

根据以前的答案只是使用的例子.它真的不清楚,但我可以展示它是如何工作的:

@interface PrettyViewController()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>
    //some code
@end

@implementation PrettyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.collectionView.delegate = self;//bingo! right here
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake([[UIScreen mainScreen] bounds].size.width, 20.0);
}


@end
Run Code Online (Sandbox Code Playgroud)