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

关键操作:

效果如下:

KMCollectionViewCell.h

 #import <UIKit/UIKit.h>

 @interface KMCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UIImageView *imgVCustom;
@property (strong, nonatomic) IBOutlet UILabel *lblDesc; @end

KMCollectionViewCell.m

 #import "KMCollectionViewCell.h"

 @implementation KMCollectionViewCell

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

ViewController.h

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate>
@property (strong, nonatomic) NSMutableArray *mArrData;
@property (strong, nonatomic) IBOutlet UICollectionView *collVCustom; @end

ViewController.m

 #import "ViewController.h"

 #import "KMCollectionViewCell.h"
@interface ViewController ()
- (void)layoutUI;
@end @implementation ViewController #define kNumberOfImage 9
#define kNumberOfCells 25
#define kNumberOfColumns 3
#define kPaddingOfScreen 20.0 - (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)layoutUI {
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"使用UICollectionView实现网格化视图效果"; //填充作为数据源的可变长数组_mArrData的数据
_mArrData = [[NSMutableArray alloc] initWithCapacity:kNumberOfCells];
for (NSUInteger i=; i<kNumberOfCells; i++) {
UIImage *imgCustom = [UIImage imageNamed:[NSString stringWithFormat:@"%lu", (i%kNumberOfImage + )]];
NSString *strDesc = [NSString stringWithFormat:@"第%lu张照片", (i+)];
//NSDictionary *dicData = @{ @"image":imgCustom, @"desc":strDesc }; //考虑字典是否是可变的,如果需要修改里面的键值对的话,建议用NSMutableDictionary //NSMutableDictionary *mDicData = [NSMutableDictionary dictionaryWithObjectsAndKeys:imgCustom, @"image", strDesc, @"desc", nil];
NSMutableDictionary *mDicData =[[NSMutableDictionary alloc] initWithDictionary:@{ @"image":imgCustom, @"desc":strDesc }];
[_mArrData addObject:mDicData];
} _collVCustom.dataSource = self;
_collVCustom.delegate = self;
//NSLog(@"%0.2f, %0.2f", _collVCustom.frame.size.width, _collVCustom.frame.size.height);
} #pragma mark - CollectionView : UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return ;
} - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return kNumberOfCells;
} - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cellIdentifier";
KMCollectionViewCell *cell = (KMCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; NSMutableDictionary *mDicData = _mArrData[indexPath.row];
cell.imgVCustom.image = mDicData[@"image"];
cell.lblDesc.text = mDicData[@"desc"];
return cell;
} - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
return nil;
} #pragma mark - CollectionView : UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
return YES;
} - (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"didHighlightItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
} - (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"didUnhighlightItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
} - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
return YES;
} - (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
return YES;
} - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *mDicData = _mArrData[indexPath.row];
mDicData[@"desc"] = @"你点击了我"; //[mDicData setValue:@"你点击了我" forKey:@"desc"];
[collectionView reloadItemsAtIndexPaths:@[indexPath]]; NSLog(@"didSelectItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
} - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
//在didSelectItemAtIndexPath执行了reloadItemsAtIndexPaths会导致didDeselectItemAtIndexPath失效不执行,所以以下打印的语句不会执行 NSLog(@"didDeselectItemAtIndexPath:, indexPath.row=%ld ", (long)indexPath.row);
} /*
#pragma mark - CollectionView : UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(80.0, 120.0);
} - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
} - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 10.0;
} - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 10.0;
} - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
return CGSizeMake(5.0, 5.0);
} - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
return CGSizeMake(5.0, 5.0);
}
*/ @end

Main.storyboard

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7701"/>
</dependencies>
<scenes>
<!--Navigation Controller-->
<scene sceneID="oO3-Ik-HpE">
<objects>
<navigationController id="o08-Aq-pMv" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="0od-Hq-cpI">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
<segue destination="vXZ-lx-hvc" kind="relationship" relationship="rootViewController" id="H4A-yf-Sf5"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="oOk-WS-MFY" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-815" y="156"/>
</scene>
<!--View Controller-->
<scene sceneID="ufC-wZ-h7g">
<objects>
<viewController id="vXZ-lx-hvc" customClass="ViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="jyV-Pf-zRb"/>
<viewControllerLayoutGuide type="bottom" id="2fi-mo-0CV"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<collectionView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" fixedFrame="YES" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="hbO-ji-Pbd">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="3" id="hGp-2R-BYr">
<size key="itemSize" width="100" height="100"/>
<size key="headerReferenceSize" width="0.0" height="0.0"/>
<size key="footerReferenceSize" width="0.0" height="0.0"/>
<inset key="sectionInset" minX="5" minY="15" maxX="5" maxY="5"/>
</collectionViewFlowLayout>
<cells>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="cellIdentifier" id="CJI-Wd-TDq" customClass="KMCollectionViewCell">
<rect key="frame" x="5" y="79" width="100" height="100"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="100" height="100"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="wx6-rJ-aIG">
<rect key="frame" x="10" y="0.0" width="80" height="80"/>
</imageView>
<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">
<rect key="frame" x="10" y="79" width="80" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
</view>
<connections>
<outlet property="imgVCustom" destination="wx6-rJ-aIG" id="X7D-YY-IXm"/>
<outlet property="lblDesc" destination="uMW-Fs-a3A" id="96U-Cz-Man"/>
</connections>
</collectionViewCell>
</cells>
</collectionView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
<navigationItem key="navigationItem" id="GSg-lv-Vzz"/>
<connections>
<outlet property="collVCustom" destination="hbO-ji-Pbd" id="1Mp-dW-6bl"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-357" y="156"/>
</scene>
</scenes>
<simulatedMetricsContainer key="defaultSimulatedMetrics">
<simulatedStatusBarMetrics key="statusBar"/>
<simulatedOrientationMetrics key="orientation"/>
<simulatedScreenMetrics key="destination" type="retina4"/>
</simulatedMetricsContainer>
</document>

结果:

 -- ::07.304 UICollectionViewDemo[:] didHighlightItemAtIndexPath:, indexPath.row=
-- ::07.305 UICollectionViewDemo[:] didUnhighlightItemAtIndexPath:, indexPath.row=
-- ::07.308 UICollectionViewDemo[:] didSelectItemAtIndexPath:, indexPath.row=
-- ::08.337 UICollectionViewDemo[:] didHighlightItemAtIndexPath:, indexPath.row=
-- ::08.337 UICollectionViewDemo[:] didUnhighlightItemAtIndexPath:, indexPath.row=
-- ::08.338 UICollectionViewDemo[:] didSelectItemAtIndexPath:, indexPath.row=

使用 UICollectionView 实现网格化视图效果的更多相关文章

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

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

  2. "UICollectionView实现带头视图和组的头视图同时存在"实现

    实现效果如下: 以前做这效果的界面,总是实现的是section的头视图,因为我一直觉得collectionView是不像UITableView那样有tableHeaderView的,所以每次实现只能是 ...

  3. UICollectionView(集合视图)以及自定义集合视图

    一.UICollectionView集合视图           其继承自UIScrollView.         UICollectionView类是iOS6新引进的API,用于展示集合视图,布局 ...

  4. iOS:集合视图UICollectionView、集合视图控制器UICollectionViewController、集合视图单元格UICollectionViewCell(创建表格的另一种控件)

    两种创建表格方式的比较:表格视图.集合视图(二者十分类似) <1>相同点:   表格视图:UITableView(位于storyboard中,通过UIViewController控制器实现 ...

  5. iOS中UICollectionView添加头视图

    参考链接:https://www.jianshu.com/p/ef57199bf34a 找了一堆的博客,写的都少了很重要的一步. //引入头部视图 -(UICollectionReusableView ...

  6. UICollectionview的头视图和尾视图

    UITableView有头视图和尾视图,那么UICollectionView有没有头视图和尾视图呢? 答案是有的. 1.新建一个类,必须继承自 UICollectionReusableView. 2. ...

  7. unity 中UGUI制作滚动条视图效果(按钮)

    1.在unity中创建一个Image作为滚动条视图的背景: 2.在Image下创建一个空物体,在空物体下创建unity自带的Scroll View组件: 3.对滑动条视图的子物体进行调整: 4.添加滚 ...

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

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

  9. IOS中集合视图UICollectionView中DecorationView的简易使用方法

    转载自:   http://www.it165.net/pro/html/201312/8575.html Decoration View是UICollectionView的装饰视图.苹果官方给的案例 ...

随机推荐

  1. [转]自定义注释@interface的用法

    一.什么是注释     说起注释,得先提一提什么是元数据(metadata).所谓元数据就是数据的数据.也就是说,元数据是描述数据的.就象数据表中的字段一样,每个字段描述了这个字段下的数据的含义.而J ...

  2. ORA-12541:TNS:无监听程序 配置Oracle Myeclipse无法连接上 花费一天时间解决掉的

    背景:自己机子做oracle服务器,其他机子可以ping得通我的机子,但是jdbc就是连不上,后来用plsql连出现无监听程序.... 我昨天重新安装Oracle后,用PL/SQL Developer ...

  3. Beaglebone Black教程Beaglebone Black中的Cloud9 IDE基本使用

    Beaglebone Black教程Beaglebone Black中的Cloud9 IDE基本使用 ​Beaglebone Black中的Cloud9 IDE基本使用 Cloud9是集成在Beagl ...

  4. C语言 · 征税程序

    算法提高 征税程序   时间限制:1.0s   内存限制:512.0MB      问题描述 税务局希望你帮他们编写一个征税程序,该程序的功能是:首先输入某公司的年销售额sale和税率rate,然后程 ...

  5. Java编程的逻辑 (66) - 理解synchronized

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  6. [算法]和为S的连续正数序列

    题目描述 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100.但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数).没多久,他 ...

  7. 根据城市表生成json数据

    T_CityManager am = new T_CityManager(); string tou = "var LAreaData=["; string value = &qu ...

  8. Git 执行更改

    Jerry 克隆库,他决定实现基本字符串操作.于是,他创建文件string.c,在添加内容到 string.c 会这个样子. #include <stdio.h> int my_strle ...

  9. CSS(九):设置盒子水平垂直居中

    通过设置下面的样式可以使盒子水平垂直居中: <!DOCTYPE html> <html lang="en"> <head> <meta c ...

  10. beansbinding NetBeans IDE 中 Swing数据绑定插件

    http://my.oschina.net/u/127459/blog/111486 https://kenai.com/projects/betterbeansbinding/pages/Home ...