使用 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的装饰视图.苹果官方给的案例 ...
随机推荐
- 2. 决策树(Decision Tree)-ID3、C4.5、CART比较
1. 决策树(Decision Tree)-决策树原理 2. 决策树(Decision Tree)-ID3.C4.5.CART比较 1. 前言 上文决策树(Decision Tree)1-决策树原理介 ...
- Ubuntu 14.04 编译 Android 4.2.2 for Tiny4412
. . . . . 在学校里是用 Redhat 6.4 编译的 Android 4.2.2 很顺利,把源码包拷贝到笔记本上的 Ubuntu 14.04 上再编译遭遇了各种坑,所以便有了这篇博客记录解决 ...
- MyBatis 之 SqlSessionManager 源码分析
MyBatis 的 4 个基本构成: SqlSessionFactoryBuilder(构造器): 根据配置信息或者代码来生成 SqlSessionFactory(工厂接口) SqlSessionFa ...
- HTTP 响应头信息(Http Response Header) Content-Length 和 Transfer-Encoding
Tomcat 中响应头信息(Http Response Header) Content-Length 和 Transfer-Encoding 客户端(PC浏览器或者手机浏览器)在接受到Tomcat的响 ...
- 隐藏的Word快捷键操作
原文地址:http://tieba.baidu.com/p/4163778583 原文来自于: 新文咖从会用电脑开始,Microsoft Office Word就是我们最常用的软件.靠着它,我们写论文 ...
- RavenDb学习(三)静态索引
在静态索引这块,RavenDb其实的是lucene,所以里面有很多概念,其实都是lucene本身的. .定义静态Indexes documentStore.DatabaseCommands.PutIn ...
- 你真的理解devDependencies和dependencies区别吗?
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/achenyuan/article/details/80899783 网上统一的观念是 devDep ...
- matlab知识点汇集
1.设置图线宽度 set( haxis, 'LineWidth', 1.0 ); ----这是 set函数, 'LineWidth'就是axis的线宽度属性,其值默认为0.5,这里可以改成1.0了 ...
- add new row to data.frame/dataframe
df<-NULL new_row<-data.frame(colA="xxx",colB=123) df<-rbind(df,new_row)
- C#注册表读写完整操作类
1.注册表基项静态域 /// <summary> /// 注册表基项静态域 ///1.Registry.ClassesRoot 对应于HKEY_CLASSES_ROOT 主键 ///2.R ...