使用iOS控件UICollectionView生成可拖动的桌面的实例

2020-01-18 18:33:04于丽

一个App受欢迎的程度,一方面来源于它本身为用户提供便捷的功能,另一方面则来源于它的UI。UI是用户体验重要的组成部分,构成UI的的元素恰恰离不开那些看似独立的控件。在开发的过程中,大家对UITableView应该很熟悉吧!确实UITableView在处理数据显示方面有着很强大的功能,例如网红们使用的微博,微信社交软件的聊天界面等等,这种流式布局使用UITableView简直最合适不过了;但毕竟UITableView不是万能的,当需要显示横纵向的数据时它就显得捉襟见肘了,虽然这也难不倒我们程序猿但是何必要大费周章的去定义复杂的cell呢!UICollectionView就是专门用来应付这种布局的,使用UICollectionView可以给我们带来以下几点优势:1.可以高度的定制内容展示的样式 2.高效的管理大量的数据。

首先给大家看一下这个Demo的效果图:

uicollectionview拖动,ios,uicollectionview,uicollectionview详解

iOS设备不知道现在有没有可以屏幕录制的app,这样我就可以把操作的动作用gif图片po上来了,大家如果有推荐可以告诉我哈!关于拖动,长按图片后就可以将图片拖到你想要的位置上,另外的图片则会依次排序,很顺畅的体验。

在使用UICollectionView的时后,我们的类需要实现这些协议:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,

UICollectionViewDelegate,UIGestureRecognizerDelegate。

UICollectionViewDataSource:和我们在UITableView中所需要实现的UITableViewDataSource是一个道理,它里面包括以下这些API:


@protocol UICollectionViewDataSource <NSObject> 
@required 
 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section; 
 
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath; 
 
@optional 
 
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView; 
 
// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: 
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath; 
 
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0); 
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0); 
 
@end 

UICollectionViewDelegateFlowLayout:UICollectionViewFlowLayout是一个专门用来管理collectionView布局的类,可以通过实现以下函数来调整我们界面的样式: