继续完善上一篇的博客
我们想在点击cell的时候能够做出相应的反应,现在着手做吧
1.我们在IKEDMyOwnHorizenView.m文件下添加下面代码
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%@",[[collectionImageData objectAtIndex:[indexPath row]] objectForKey:@"title"]);
}
结果是能够打印出标题的,如果我们想让这个标题在界面上打印出来,该怎么办呢?这就是传递参数的问题了,最好的回传参数的问题就目前我学习的范围来说是代理传值(PS:本人新手,所以针对我来说的,学无止尽,我需要更加努力了)
2.创建代理(最近看了一本教程,虽然有点老但是收获蛮大)
(1)在头文件中声称自己要引用的类,其实也就是自己
(2)在.h文件定义代理对象要实现的协议
(3)将代理对象最为自己的一个属性存在
(4)在被代理对象合适的时候执行代理方法
(5)在代理对象的头文件或者.m文件中声明代理
(6)实现代理对象的方法
(7)告诉被代理对象代理对象是谁
好了,总结完毕,上代码了
3.在IKEDMyOwnHorizenViewDelegate.h文件实现代理声明以及相应方法的声明
//
// IKEDMyOwnHorizenView.h
// Ikefr
//
// Created by apple on 14-2-27.
// Copyright (c) 2014年 com.tyust. All rights reserved.
//
#import <UIKit/UIKit.h>
@class IKEDMyOwnHorizenView;
@protocol IKEDMyOwnHorizenViewDelegate <NSObject>
-(void)getData:(IKEDMyOwnHorizenView *)ikedView fromSelectedCellAtIndexpathString:(NSString*)str;
@end
@interface IKEDMyOwnHorizenView : UIView<UICollectionViewDataSource,UICollectionViewDelegate>
@property(weak,nonatomic)id<IKEDMyOwnHorizenViewDelegate> delegate;
@property(nonatomic,strong)UICollectionView *myCollectionView;
-(void)setImgData:(NSArray*)array;
@end
4.在用户点击cell的时候调用代理方法,在IKEDMyOwnHorizenView.文件中添加下面的代码
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str =[[collectionImageData objectAtIndex:[indexPath row]] objectForKey:@"title"];
[self.delegate getData:self fromSelectedCellAtIndexpathString:str];
NSLog(@"sadsad");
}
5.在代理对象中实现相应的代理方法,在IKEDMyOwnHorizenView.m中实现代理方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str =[[collectionImageData objectAtIndex:[indexPath row]] objectForKey:@"title"];
[self.delegate getData:self fromSelectedCellAtIndexpathString:str];
}
6.在实例化被代理对象的时候,就告诉他的代理对象是谁
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.itemSize = CGSizeMake(100, 100);
flowLayout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
flowLayout.minimumInteritemSpacing = 10;
_myCollectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:flowLayout];
_myCollectionView.dataSource = self;
_myCollectionView.delegate = self;
_myCollectionView.showsHorizontalScrollIndicator = NO;
self.backgroundColor = [UIColor whiteColor];
[_myCollectionView registerClass:[IKEDMyOwnImgView class] forCellWithReuseIdentifier:@"IKeD"];
[self addSubview:_myCollectionView];
}
return self;
}
7.大功告成,结果如下