使用 UICollectionView 实现网格化视图效果
讲解 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 实现网格化视图效果的更多相关文章
- 用FireFox火狐浏览器的3D Tilt 插件查看网页3D视图效果
逛博客发现了网页的3D视图效果,一搜原来是Firefox特有的一个功能,先看效果: 相当炫酷,接下来介绍如何实现. 1.首先安装3d tilt 插件: 从火狐浏览器的添加插件页面,搜索:3D Tilt ...
- "UICollectionView实现带头视图和组的头视图同时存在"实现
实现效果如下: 以前做这效果的界面,总是实现的是section的头视图,因为我一直觉得collectionView是不像UITableView那样有tableHeaderView的,所以每次实现只能是 ...
- UICollectionView(集合视图)以及自定义集合视图
一.UICollectionView集合视图 其继承自UIScrollView. UICollectionView类是iOS6新引进的API,用于展示集合视图,布局 ...
- iOS:集合视图UICollectionView、集合视图控制器UICollectionViewController、集合视图单元格UICollectionViewCell(创建表格的另一种控件)
两种创建表格方式的比较:表格视图.集合视图(二者十分类似) <1>相同点: 表格视图:UITableView(位于storyboard中,通过UIViewController控制器实现 ...
- iOS中UICollectionView添加头视图
参考链接:https://www.jianshu.com/p/ef57199bf34a 找了一堆的博客,写的都少了很重要的一步. //引入头部视图 -(UICollectionReusableView ...
- UICollectionview的头视图和尾视图
UITableView有头视图和尾视图,那么UICollectionView有没有头视图和尾视图呢? 答案是有的. 1.新建一个类,必须继承自 UICollectionReusableView. 2. ...
- unity 中UGUI制作滚动条视图效果(按钮)
1.在unity中创建一个Image作为滚动条视图的背景: 2.在Image下创建一个空物体,在空物体下创建unity自带的Scroll View组件: 3.对滑动条视图的子物体进行调整: 4.添加滚 ...
- Android UI视图效果篇之仿QQ好友列表分组悬浮PinnedHeaderExpandableListView
楼主是在平板上測试的.图片略微有点大,大家看看效果就好 接下来贴源代码: PinnedHeaderExpandableListView.java 要注意的是 在 onGroupClick方法中pare ...
- IOS中集合视图UICollectionView中DecorationView的简易使用方法
转载自: http://www.it165.net/pro/html/201312/8575.html Decoration View是UICollectionView的装饰视图.苹果官方给的案例 ...
随机推荐
- 实践 ArcGIS Web 3D
ArcGIS 产品家族的 Web 3D 功能众多用户期待已久.从 ArcGIS 10.3.1 版本号開始,Esri 放了个大招,千呼万唤始出来的 Web 3D 功能,最终不再犹抱琵琶半遮面了. 那究竟 ...
- How Not to Crash #6: Properties and Accessors(属性,存储器方法使问题)
How Not to Crash #6: Properties and Accessorshtml, body {overflow-x: initial !important;}html { font ...
- java你可能不知道的事(2)--堆和栈<转>
在java语言的学习和使用当中你可能已经了解或者知道堆和栈,但是你可能没有完全的理解它们.今天我们就一起来学习堆.栈的特点以及它们的区别.认识了这个之后,你可能对java有更深的理解. Java堆内存 ...
- SqlServer 自动化分区方案
本文是我关于数据库分区的方案的一些想法,或许有些问题.仅供大家讨论.SqlServer (SqlServer 2005\SqlServer 2008)实现分区需要在企业版下进行. SqlServer的 ...
- 1px的border
css中是这样写的: div{ border-bottom: 1px solid #dfe5e4; } 但在手机上,像素比不为 1 ,由于 webview 的灰度渲染, border 一般会显示为 2 ...
- 2012Google校园招聘笔试题
1.已知两个数字为1~30之间的数字,甲知道两数之和,乙知道两数之积,甲问乙:“你知道是哪两个数吗?”乙说:“不知道”.乙问甲:“你知道是哪两个数吗?”甲说:“也不知道”.于是,乙说:“那我知道了”, ...
- HTML5数据推送SSE原理及应用开发
JavaScript表达行为,CSS表达外观,注意HTML既表达结构(逻辑结构),又表达内容(数据本身)通常需要更新数据时,并不需要更新结构,正是这种不改变组织结构仅改变数据的诉求,推动了数据拉取和数 ...
- @Resource、@Autowired跟default-autowire区别联系
@Resource.@Autowired和default-autowire区别联系 今天看了一工程,里面既有default-autowire,又有@Autowired,还有@Resource.我就不明 ...
- 微信小程序——video使用总结
关于小程序video的一些基本使用方法,可点击这里稍作了解. 需求: 1.默认显示封面: 2.一个视频播放的时候,其他视频停止播放,并显示封面. 解决问题思路: 1.通过wx:if判断当前视频是否是播 ...
- Java设计模式(20)观察者模式(Observer模式)
Java深入到一定程度,就不可避免的碰到设计模式(design pattern)这一概念,了解设计模式,将使自己对java中的接口或抽象类应用有更深的理解.设计模式在java的中型系统中应用广泛,遵循 ...