IOS开发学习分享(一)——StoryBoard的UICollectionView和UINavigationView的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/madonghyu/article/details/81143494

首先贴一下CollectionView的结构图
结构图


一、UICollectionView和UINavigationView构成

1.Xcode的storyboard开发十分的方便,新建一个UICollectionView可以直接通过上图右下角的组件直接拖拽得到。
2.UINavigationView的添加也是十分的简单,如图:
这里写图片描述
选中UICollectionView的Scene,然后点击Navigation Controller就可以了。
3.UICollectionViewCell的添加也可以通过右下角的组件拖拽形成。
4.接下来就是controller层和view层的结合了。通过storyboard定义的视图模板,要实现数据的动态展示,就需要自定义的controller辅助。
这里写图片描述
这里要注意的是Inherit Module From Target这个选项最好不要选,否则可能会导致自定义的类找不到而报错。。。


先贴一下博主的controller的代码(删减了业务相关的代码)

头文件

@interface ClassifyController : UICollectionViewController <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NSURLSessionDataDelegate>
@property (strong, nonatomic)
IBOutletCollection(UICollectionView) NSArray *collection;
//视频分类的id
@property(nonatomic,readwrite) NSArray *categories;
//网络得到的数据
@property(nonatomic,readwrite) NSMutableData *result;
@end

实现

@implementation ClassifyController
static NSString * CellIdentifier = @"cell";

- (void)viewDidLoad {
    _categories = [NSArray new];
    _result = [NSMutableData new];
    [super viewDidLoad];
}

//定义展示的cell的数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _categories.count;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//这里使用的是自定义的cell
    ClassifyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    return cell;
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//cell的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  ..........
}

下面说一下博主遇到的一些坑。

  • Cell的显示,在storyboard定义的cell,如果你不是想弄多种不同格式的cell,那么是需要拖拽一个cell,这里十分重要的一件事情是,必须给cell指定一个identifier,名字自己随意起,如果不指定的话cell是不会显示的。这里写图片描述
  • 由于博主是想做动态的数据展示,所以cell的数目是动态变化的,实现方案从网上找到的大多数都是在controller里面定义一个数组,然后根据数组的长度定义cell的数目。
  • 而关于cell视图的刷新,由于博主是异步的读取数据,刷新的时候不是在UI的主线程里,所以需要使用这样的代码刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });

这里的self.collectionView也是一个需要注意的地方,在storyboard开发里面,有一个叫Referencing Outlet CollectionsReferencing Outlets的东西,具体就是在视图编辑里面右键就可以看到了。关于这两个东西的区别和作用,网上很多。
这里要注意的是,collectionView是绑定了UICllectionView的Referencing Outlet Collections,博主开发的时候使用Referencing Outlets会报错。。。


猜你喜欢

转载自blog.csdn.net/madonghyu/article/details/81143494