讲解 UICollectionView 的相关链接:http://blog.csdn.net/eqera/article/details/8134986

关键操作:

效果如下:

KMCollectionViewCell.h

1 #import <UIKit/UIKit.h>
2
3 @interface KMCollectionViewCell : UICollectionViewCell
4 @property (strong, nonatomic) IBOutlet UIImageView *imgVCustom;
5 @property (strong, nonatomic) IBOutlet UILabel *lblDesc;
6
7 @end

KMCollectionViewCell.m

 1 #import "KMCollectionViewCell.h"
 2
 3 @implementation KMCollectionViewCell
 4
 5 - (id)initWithFrame:(CGRect)frame { //由于没调用,所以不会触发initWithFrame方法
 6     if (self = [super initWithFrame:frame]) {
 7         //Some codes as the content of drawRect's method
 8     }
 9     return self;
10 }
11
12 - (void)drawRect:(CGRect)rect { //drawRect方法会在每次对象实例化时调用
13     _imgVCustom.layer.masksToBounds = YES;
14     _imgVCustom.layer.cornerRadius = _imgVCustom.frame.size.width/2.0; //设置圆角;当值为正方形图片视图的宽度一半时,就为圆形
15
16     _lblDesc.adjustsFontSizeToFitWidth = YES; //设置是否根据内容自适应调整字体大小;默认值为NO
17 }
18
19 @end

ViewController.h

1 #import <UIKit/UIKit.h>
2
3 @interface ViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate>
4 @property (strong, nonatomic) NSMutableArray *mArrData;
5 @property (strong, nonatomic) IBOutlet UICollectionView *collVCustom;
6
7 @end

ViewController.m

  1 #import "ViewController.h"
  2
  3 #import "KMCollectionViewCell.h"
  4 @interface ViewController ()
  5 - (void)layoutUI;
  6 @end
  7
  8 @implementation ViewController
  9
 10 #define kNumberOfImage 9
 11 #define kNumberOfCells 25
 12 #define kNumberOfColumns 3
 13 #define kPaddingOfScreen 20.0
 14
 15 - (void)viewDidLoad {
 16     [super viewDidLoad];
 17
 18     [self layoutUI];
 19 }
 20
 21 - (void)didReceiveMemoryWarning {
 22     [super didReceiveMemoryWarning];
 23     // Dispose of any resources that can be recreated.
 24 }
 25
 26 - (void)layoutUI {
 27     self.view.backgroundColor = [UIColor whiteColor];
 28     self.navigationItem.title = @"使用UICollectionView实现网格化视图效果";
 29
 30     //填充作为数据源的可变长数组_mArrData的数据
 31     _mArrData = [[NSMutableArray alloc] initWithCapacity:kNumberOfCells];
 32     for (NSUInteger i=0; i<kNumberOfCells; i++) {
 33         UIImage *imgCustom = [UIImage imageNamed:[NSString stringWithFormat:@"%lu", (i%kNumberOfImage + 1)]];
 34         NSString *strDesc = [NSString stringWithFormat:@"第%lu张照片", (i+1)];
 35         //NSDictionary *dicData = @{ @"image":imgCustom, @"desc":strDesc }; //考虑字典是否是可变的,如果需要修改里面的键值对的话,建议用NSMutableDictionary
 36
 37         //NSMutableDictionary *mDicData = [NSMutableDictionary dictionaryWithObjectsAndKeys:imgCustom, @"image", strDesc, @"desc", nil];
 38         NSMutableDictionary *mDicData =[[NSMutableDictionary alloc] initWithDictionary:@{ @"image":imgCustom, @"desc":strDesc }];
 39         [_mArrData addObject:mDicData];
 40     }
 41
 42     _collVCustom.dataSource = self;
 43     _collVCustom.delegate = self;
 44     //NSLog(@"%0.2f, %0.2f", _collVCustom.frame.size.width, _collVCustom.frame.size.height);
 45 }
 46
 47 #pragma mark - CollectionView : UICollectionViewDataSource
 48 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
 49     return 1;
 50 }
 51
 52 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
 53     return kNumberOfCells;
 54 }
 55
 56 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 57     static NSString *cellIdentifier = @"cellIdentifier";
 58     KMCollectionViewCell *cell = (KMCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
 59
 60     NSMutableDictionary *mDicData = _mArrData[indexPath.row];
 61     cell.imgVCustom.image = mDicData[@"image"];
 62     cell.lblDesc.text = mDicData[@"desc"];
 63     return cell;
 64 }
 65
 66 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
 67     // The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
 68     return nil;
 69 }
 70
 71 #pragma mark - CollectionView : UICollectionViewDelegate
 72 - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
 73     return YES;
 74 }
 75
 76 - (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
 77     NSLog(@"didHighlightItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
 78 }
 79
 80 - (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
 81     NSLog(@"didUnhighlightItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
 82 }
 83
 84 - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
 85     return YES;
 86 }
 87
 88 - (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
 89     return YES;
 90 }
 91
 92 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
 93     NSMutableDictionary *mDicData = _mArrData[indexPath.row];
 94     mDicData[@"desc"] = @"你点击了我"; //[mDicData setValue:@"你点击了我" forKey:@"desc"];
 95     [collectionView reloadItemsAtIndexPaths:@[indexPath]];
 96
 97     NSLog(@"didSelectItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
 98 }
 99
100 - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
101     //在didSelectItemAtIndexPath执行了reloadItemsAtIndexPaths会导致didDeselectItemAtIndexPath失效不执行,所以以下打印的语句不会执行
102
103     NSLog(@"didDeselectItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
104 }
105
106 /*
107 #pragma mark - CollectionView : UICollectionViewDelegateFlowLayout
108 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
109     return CGSizeMake(80.0, 120.0);
110 }
111
112 - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
113     return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
114 }
115
116 - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
117     return 10.0;
118 }
119
120 - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
121     return 10.0;
122 }
123
124 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
125     return CGSizeMake(5.0, 5.0);
126 }
127
128 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
129     return CGSizeMake(5.0, 5.0);
130 }
131 */
132
133 @end

Main.storyboard

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="7702" systemVersion="14D136" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="o08-Aq-pMv">
 3     <dependencies>
 4         <deployment identifier="iOS"/>
 5         <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7701"/>
 6     </dependencies>
 7     <scenes>
 8         <!--Navigation Controller-->
 9         <scene sceneID="oO3-Ik-HpE">
10             <objects>
11                 <navigationController id="o08-Aq-pMv" sceneMemberID="viewController">
12                     <navigationBar key="navigationBar" contentMode="scaleToFill" id="0od-Hq-cpI">
13                         <rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
14                         <autoresizingMask key="autoresizingMask"/>
15                     </navigationBar>
16                     <connections>
17                         <segue destination="vXZ-lx-hvc" kind="relationship" relationship="rootViewController" id="H4A-yf-Sf5"/>
18                     </connections>
19                 </navigationController>
20                 <placeholder placeholderIdentifier="IBFirstResponder" id="oOk-WS-MFY" userLabel="First Responder" sceneMemberID="firstResponder"/>
21             </objects>
22             <point key="canvasLocation" x="-815" y="156"/>
23         </scene>
24         <!--View Controller-->
25         <scene sceneID="ufC-wZ-h7g">
26             <objects>
27                 <viewController id="vXZ-lx-hvc" customClass="ViewController" sceneMemberID="viewController">
28                     <layoutGuides>
29                         <viewControllerLayoutGuide type="top" id="jyV-Pf-zRb"/>
30                         <viewControllerLayoutGuide type="bottom" id="2fi-mo-0CV"/>
31                     </layoutGuides>
32                     <view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
33                         <rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
34                         <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
35                         <subviews>
36                             <collectionView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" fixedFrame="YES" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="hbO-ji-Pbd">
37                                 <rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
38                                 <color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
39                                 <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="3" id="hGp-2R-BYr">
40                                     <size key="itemSize" width="100" height="100"/>
41                                     <size key="headerReferenceSize" width="0.0" height="0.0"/>
42                                     <size key="footerReferenceSize" width="0.0" height="0.0"/>
43                                     <inset key="sectionInset" minX="5" minY="15" maxX="5" maxY="5"/>
44                                 </collectionViewFlowLayout>
45                                 <cells>
46                                     <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="cellIdentifier" id="CJI-Wd-TDq" customClass="KMCollectionViewCell">
47                                         <rect key="frame" x="5" y="79" width="100" height="100"/>
48                                         <autoresizingMask key="autoresizingMask"/>
49                                         <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
50                                             <rect key="frame" x="0.0" y="0.0" width="100" height="100"/>
51                                             <autoresizingMask key="autoresizingMask"/>
52                                             <subviews>
53                                                 <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="wx6-rJ-aIG">
54                                                     <rect key="frame" x="10" y="0.0" width="80" height="80"/>
55                                                 </imageView>
56                                                 <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="uMW-Fs-a3A">
57                                                     <rect key="frame" x="10" y="79" width="80" height="21"/>
58                                                     <fontDescription key="fontDescription" type="system" pointSize="17"/>
59                                                     <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
60                                                     <nil key="highlightedColor"/>
61                                                 </label>
62                                             </subviews>
63                                             <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
64                                         </view>
65                                         <connections>
66                                             <outlet property="imgVCustom" destination="wx6-rJ-aIG" id="X7D-YY-IXm"/>
67                                             <outlet property="lblDesc" destination="uMW-Fs-a3A" id="96U-Cz-Man"/>
68                                         </connections>
69                                     </collectionViewCell>
70                                 </cells>
71                             </collectionView>
72                         </subviews>
73                         <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
74                     </view>
75                     <navigationItem key="navigationItem" id="GSg-lv-Vzz"/>
76                     <connections>
77                         <outlet property="collVCustom" destination="hbO-ji-Pbd" id="1Mp-dW-6bl"/>
78                     </connections>
79                 </viewController>
80                 <placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
81             </objects>
82             <point key="canvasLocation" x="-357" y="156"/>
83         </scene>
84     </scenes>
85     <simulatedMetricsContainer key="defaultSimulatedMetrics">
86         <simulatedStatusBarMetrics key="statusBar"/>
87         <simulatedOrientationMetrics key="orientation"/>
88         <simulatedScreenMetrics key="destination" type="retina4"/>
89     </simulatedMetricsContainer>
90 </document>

结果:

1 2015-06-07 11:34:07.304 UICollectionViewDemo[720:21215] didHighlightItemAtIndexPath:, indexPath.row=15
2 2015-06-07 11:34:07.305 UICollectionViewDemo[720:21215] didUnhighlightItemAtIndexPath:, indexPath.row=15
3 2015-06-07 11:34:07.308 UICollectionViewDemo[720:21215] didSelectItemAtIndexPath:, indexPath.row=15
4 2015-06-07 11:34:08.337 UICollectionViewDemo[720:21215] didHighlightItemAtIndexPath:, indexPath.row=19
5 2015-06-07 11:34:08.337 UICollectionViewDemo[720:21215] didUnhighlightItemAtIndexPath:, indexPath.row=19
6 2015-06-07 11:34:08.338 UICollectionViewDemo[720:21215] didSelectItemAtIndexPath:, indexPath.row=19 

使用 UICollectionView 实现网格化视图效果相关推荐

  1. 用FireFox火狐浏览器的3D Tilt 插件查看网页3D视图效果

    逛博客发现了网页的3D视图效果,一搜原来是Firefox特有的一个功能,先看效果: 相当炫酷,接下来介绍如何实现. 1.首先安装3d tilt 插件: 从火狐浏览器的添加插件页面,搜索:3D Tilt ...

  2. 白鹭引擎实现滚动视图效果

    白鹭引擎实现滚动视图效果 话不多说,直接上代码了 先声明一个私有的计数器,定义滚动试图的上下翻变量 private PageturnTime:egret.Timer = null; private p ...

  3. UICollectionView的sectionHeader悬浮效果

    collectionView没有类似于tableView的Plain效果(即sectionHeader悬浮),不过可以通过自定义flowLayout实现,因此它比tableView拥有更强大的扩展性, ...

  4. UIcollectionView 加入尾部视图

    2019独角兽企业重金招聘Python工程师标准>>> static NSString *identify = @"collectionViewCell"; st ...

  5. 【Android视图效果】共享元素实现仿微信查看大图效果

    在之前的文章中,我们通过动画实现了这个,具体可以查看[Android 动画]动画详解之仿微信查看大图效果(四),这里,我们用过度动画来实现. 什么是共享元素? 它是Android 5.0新加入的一种过 ...

  6. Android UI视图效果篇之仿QQ好友列表分组悬浮PinnedHeaderExpandableListView

    楼主是在平板上测试的,图片稍微有点大,大家看看效果就好 接下来贴源码: PinnedHeaderExpandableListView.java 要注意的是 在 onGroupClick方法中paren ...

  7. android实现评论列表_【Android视图效果】分组列表实现吸顶效果

    效果图 效果图 分析 先来分析一下,可以看到这是一个按月份分组的2行图片列表,列表顶部一个悬浮栏,会随着列表滑动而刷新,点击顶部栏,弹出了一个筛选框. 思路 1.列表部分 可以用RecyclerVie ...

  8. 导航栏透明度渐变; 下拉头视图拉伸效果;勾号动画; 一段文字中点击部分可响应不同事件...

    之前通过设置navigationBar的barTintColor设置导航栏颜色,然后拿到self.navigationController.navigationBar.subviews.firstOb ...

  9. 集合视图UICollectionView 介绍及其示例程序

    UICollectionView是一种新的数据展示方式,简单来说可以把它理解成多列的UITableView.如果你用过iBooks的话,可 能你还对书架布局有一定印象,一个虚拟书架上放着你下载和购买的 ...

  10. UICollectionView的基本使用(1)

    如果是简单实用UICollectionView的话,用法和UITableView基本一致.下面是用UICollectionView实现的简单图片显示 (1)打开storyboard,将一个UIColl ...

最新文章

  1. WinCE项目应用之车载导航
  2. Mac下 Brew 更新缓慢问题解决(配置清华大学开源软件镜像站)
  3. struts2注解总结----@Action和@Result
  4. mysql 乐观锁 version_乐观锁-version的使用
  5. VTK:PolyData之PointLocatorRadius
  6. HDU3662(求三维凸包表面的多边形个数,表面三角形个数,体积,表面积,凸包重心,凸包中点到面的距离)
  7. 仓库每天的账怎样做_新年第一站,济南:仓储匠人仓库问题解决与实战力培训...
  8. 提示丢失libgcc_s_dw2-1.dll问题
  9. android系统特效详解和修改方法
  10. Python编程基础10:列表
  11. opencv实现多个图拼接成一个图
  12. 分子模拟的理论与实践_基于分子模拟的数据驱动发现流体力学宏观方程
  13. 山东CIO智库会员参观徐工信息公司
  14. SuperWebSocket发布0.1版本
  15. POI:Excel表解析与导出通用工具类
  16. chrome 历史版本下载
  17. 2022新版千月影视双端APP带H5功能开源程序支持当面付和易支付
  18. 用户画像标签体系建设指南
  19. HIVE最全面入门指南
  20. 原创分享 | 如何从非技术层面实现数据驱动

热门文章

  1. protoc安装使用
  2. Dilated Convolutions 空洞卷积
  3. 微信小程序实现底部导航栏自定义tabBar
  4. matlab中的ifftshift的用法,如何在R中写fftshift和ifftshift?
  5. mysql数据库保存微信emoji表情
  6. python Django项目汇总(毕设、课设、学习)
  7. 手机html5跑分,吊炸天的Chrome55内核来袭 360手机浏览器成“跑分王”
  8. 如何查看AT24C02设备地址
  9. mac 配置mysql 环境变量
  10. 【python】websockets