使用 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的装饰视图.苹果官方给的案例 ...
 
随机推荐
- golang包管理的取巧
			
常见的golang的包管理工具 glide 使用yaml做配置,语义化版本管理,可以设置镜像,下载x系列库,但是x系列库被第三方库依赖时会出现下载失败. dep 亲儿子,语义化版本管理,无法解决墙 v ...
 - iis下php 500错误
			
很不想用iis,然而客户不想增加机器,只好按客户的意思了.可是没想到发送短信以在本地 机器上是好的,在iis下直接500. 一开始以为是防火墙问题,后来检查了一下没有,再后来换了一个短信接口, ...
 - [转]Oracle的update语句优化研究
			
原文地址:http://blog.csdn.net/u011721927/article/details/39228001 一. update语句的语法与原理 1. 语法 单表 ...
 - Cacti的库表结构-Data
			
cacti 的数据都是存放在rrdtool 中的,数据库存放的其实只是配置数据,cacti 的逻辑对象主要分为三种,data (数据).graph (图片).host (设备),这在它的表设计中也能很 ...
 - GIT——总结.1-
			
创建版本库 时光机穿梭 版本回退 工作区和暂存区 管理修改 撤销修改 删除文件 Git Git是目前世界上最先进的分布式版本控制系统(没有之一) Git是分布式版本控制系统 首先,分布式版本控制系统根 ...
 - kafka中的消费组
			
一直以来都想写一点关于kafka consumer的东西,特别是关于新版consumer的中文资料很少.最近Kafka社区邮件组已经在讨论是否应该正式使用新版本consumer替换老版本,笔者也觉得时 ...
 - Spring Cloud Config 配置中心 自动加解密功能 jasypt方式
			
使用此种方式会存在一种问题:如果我配置了自动配置刷新,则刷新过后,加密过后的密文无法被解密.具体原因分析,看 SpringCloud 详解配置刷新的原理 使用 jasypt-spring-boot- ...
 - 解决:According to TLD or attribute directive in tag file, attribute value does not accept any express。
			
http://blog.csdn.net/lzblog/article/details/22076893 ——————————————————————————————————————————————— ...
 - R语言日期的表示和运算(详细总结)
			
1.取出当前日期 Sys.Date() [1] "2014-10-29" date() #注意:这种方法返回的是字符串类型 [1] "Wed Oct 29 20:36: ...
 - 关于Unity中变量和函数的定义
			
变量 1.匀速运动的物体都要记得定义一个speed速度变量 2.不断产生很多相同物体的事件要记得定义时间生成物体的间隔rate,并且有一个一达到rate的值就清0的累加时间变量,累加时间变量是通过Ti ...