如何水平和垂直滚动collectionview单元格.我使用的是9单元格collectionview



我对集合视图完全陌生,请帮助我在集合视图中垂直和水平滚动单元格:

viewcontroller.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
{
UICollectionView *collectionView;
}
@end

viewcontroller.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame 
collectionViewLayout:layout];
    [collectionView setDataSource:self];
    [collectionView setDelegate:self];
    [collectionView registerClass:[UICollectionViewCell class] 
forCellWithReuseIdentifier:@"cellIdentifier"];
    [collectionView setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:collectionView];
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 9;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(100, 100);
}
@end

我来晚了一点,但为了防止其他人查看,您可以使用UICollectionViewFlowLayout轻松设置集合视图滚动方向。

  1. 创建UICollectionViewFlowLayout的实例
  2. 将滚动方向设置为UICollectionViewScrollDirectionHorizontal
  3. 高兴。

    -(instancetype)init{UICollectionViewFlowLayout*布局=[[UICollectionViewFlow布局分配]init];layout.itemSize=CGSizeMake(106106);layout.minimumInteritemSpacing=1;layout.minimumLineSpacing=1;layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;self=[super-initWithCollectionViewLayout:layout];回归自我;}

您可以使用UICollectionView类的以下方法以编程方式滚动集合视图:

[collectionView scrollsToTop];
[collectionView scrollToItemAtIndexPath:<#(NSIndexPath *)#> atScrollPosition:<#(UICollectionViewScrollPosition)#> animated:<#(BOOL)#>];
[collectionView scrollRectToVisible:<#(CGRect)#> animated:<#(BOOL)#>];

最新更新