iOS-UICollectionViewController 介紹,iosuicollectionview

來源:互聯網
上載者:User

iOS-UICollectionViewController 介紹,iosuicollectionview

廢話不多說,列幾個列子 (幾種情況下的做法):

 

情景一:

介紹:1. 在UIViewController 上加 UICollectionView (用代碼 建立 UICollectionView)。

   2. UICollectionView上的cell為自訂的view,名字叫:MyDealCell,用的是 xib。 ( 建立類 MyDealCell 繼承自 UICollectionViewCell )

   3. 選中 MyDealCell.xib 修改其 identifier 為 ListCell。

   4. 註冊 cell 用 registerClass 。

     5. 在iPad上測試。

 

=======GoodListViewController.h=======

@interface GoodListViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@end

 

=======GoodListViewController.m=======

 

static NSString * const reuseIdentifier = @"ListCell";

- (void)viewDidLoad {
    [super viewDidLoad];

    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
    collection=[[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    collection.dataSource=self;
    collection.delegate=self;
    collection.backgroundColor=[UIColor redColor];
    [self.view addSubview:collection];

    // [self.collectionView registerNib:[UINib nibWithNibName:@"MyDealCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier]; // MyDealCell用Xib實現的
    [collection registerClass:[GoodListCell class] forCellWithReuseIdentifier:reuseIdentifier]; // GoodListCell 裡面的控制項既可以用代碼實現,也可以用xib,用xib的話,在 GoodListCell 裡面要通過 GoodListCell *goodsView = [[NSBundle mainBundle] loadNibNamed:@"CollectionCell" owner:self options:nil][0]; 載入xib。
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 23;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

  // 在 [collection dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];中的 collection 和 上面 形參 collectionView 一樣
    MyDealCell *cell=[collection dequeueReusableCellWithReuseIdentifier:reuseIdentifier  forIndexPath:indexPath];
    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(Screen_Width/3-10, Screen_Height-104);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(20, 7.5, 20, 7.5);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 7.5;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}

 

情景二:

介紹:1. GoodListViewController 繼承自 UICollectionViewController

   2. UICollectionView上的cell為自訂的view,名字叫:MyDealCell,用的是 xib。( 建立類 MyDealCell 繼承自 UICollectionViewCell )

   3. 選中 MyDealCell.xib 修改其 identifier 為 ListCell。

   4. 註冊cell用 registerNib

   5. 例子是在iPad上運行調試。

 

=======GoodListViewController.h=======

@interface GoodListViewController : UICollectionViewController

@end

 

static NSString * const reuseIdentifier = @"ListCell";


- (instancetype)init
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // cell的大小
    layout.itemSize = CGSizeMake(305, 305);
    return [self initWithCollectionViewLayout:layout];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.collectionView.backgroundColor = [UIColor redColor];
  
    // Register cell classes
    [self.collectionView registerNib:[UINib nibWithNibName:@"MTDealCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.alwaysBounceVertical = YES;
    
 //   // 添加上拉載入
 //   [self.collectionView addFooterWithTarget:self action:@selector(loadMoreDeals)];
}


/**
 當旋轉螢幕,控制器view的尺寸發生改變調用
 */
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    // 根據螢幕寬度決定列數
    int cols = (size.width == 1024) ? 3 : 2;
    
    // 根據列數計算內邊距
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    CGFloat inset = (size.width - cols * layout.itemSize.width) / (cols + 1);
    layout.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset);
    
    // 設定每一行之間的間距
    layout.minimumLineSpacing = 50;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 計算一遍內邊距
    [self viewWillTransitionToSize:CGSizeMake(collectionView.width, 0) withTransitionCoordinator:nil];
  
    return 30;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MTDealCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
     GoodListCell *cell=[collection dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
       cell.backgroundColor = [UIColor yellowColor];
       return cell;
}

#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
  NSLog(@"=====selected=indexPath.item", indexPath.item);
}

 

 

情景三:

介紹:1. ViewController 繼承自 UIViewController

     2. 在ViewController 控制器對應的故事版中直接拉一個 UICollectionView 控制項。然後連線到控制器。

   3. UICollectionView上的cell為自訂的view,名字叫:CollectionCell,用的是 xib。( 建立類 CollectionCell 繼承自 UICollectionViewCell )

     4. 選中剛剛建立的xib,更改類名為 CollectionCell

   5. 控制器中註冊cell用 registerClass

   6. 例子在iphone上運行。

   6. 這個和上兩中情景不一樣的地方是:在控制器中用 registerClass,載入 CollectionCell 對應的 xib 的時候,是在 CollectionCell.m 中通過:

       NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CollectionCell" owner:self options:nil];載入的。

 

     上面的情景一:在控制器中用 registerClass 的時候,cell裡面的控制項是用代碼實現的;

   上面的情景二:在控制器中用 registerNib 的時候,   cell裡面的控制項是在xib中實現的。

  

 

一、自訂Cell

 

1、建立類CollectionCell繼承自UICollectionViewCell

2、建立Xib,命名為CollectionCell.xib

  a.選中CollectionCell.xib刪掉預設的View,從控制項中拖一個Collection View Cell(圖3)到畫布中,設定大小為95*116

  b.選中剛剛建立的xib,更改類名為CollectionCell

  c.在CollectionCell.xib的CollectionCell中添加一個Label, 然後連線。

 

==========CollectionCell.m , 重寫 initWithFrame 方法 =============

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // 初始化時載入collectionCell.xib檔案
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"CollectionCell" owner:self options:nil];
        
        // 如果路徑不存在,return nil
        if (arrayOfViews.count < 1)
        {
            return nil;
        }
        // 如果xib中view不屬於UICollectionViewCell類,return nil
        if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]])
        {
            return nil;
        }
        // 載入nib
        self = [arrayOfViews objectAtIndex:0];
    }
    return self;
}

 

二、定義UICollectionView;

1、拖動一個Collection View到指定 ViewController控制器 的View上

2、連線dataSource和delegate,並建立映射(連線),命名 (在控制器中用這個屬性) 為CollectionView

3、選中CollectionView的尺規,將Cell Size的Width和Height改成與自訂的Cell一樣的95*116,

4、選中CollectionView的屬性,可以修改其屬性,比如是垂直滑動,還是水平滑動,選擇Vertical或Horizontal

5、選中CollectionViewCell,修改Class,繼承自CollectionCell。

 

=======ViewController.h=======

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController


@end

 

=======ViewController.m=======

#import "ViewController.h"
#import "CollectionCell.h"

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;  // 通過連線建立的屬性


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    self.collectionView.backgroundColor = [UIColor grayColor];
    [self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;

}

//每個section的item個數
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 40;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
//    
//    //圖片名稱
//    NSString *imageToLoad = [NSString stringWithFormat:@"%d.png", indexPath.row];
//    //載入圖片
//    cell.imageView.image = [UIImage imageNamed:imageToLoad];
//    //設定label文字
//    cell.label.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.row,(long)indexPath.section];
    
   CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell"forIndexPath:indexPath];
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"===indexPath.item=%d", (int)indexPath.item);
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.