使用 UICollectionView 实现网格化视图效果

讲解 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 

 

posted @ 2015-06-14 16:51  KenmuHuang  阅读(6346)  评论(0编辑  收藏  举报
如果您看完本篇博文,觉得对您有所收获,请点击右下角的 [推荐]
如果您想转载,请注明出处(原创内容,请尊重个人劳动成果)
如果您有任何意见或建议,欢迎留言
感谢您的阅读,敬请关注我的后续博客文章