美文网首页
iOS UIKit之UICollectionView

iOS UIKit之UICollectionView

作者: 小白和小黑 | 来源:发表于2015-04-08 09:35 被阅读965次
      学习iOS最多的控件是UITableView和UICollectionView,只要做APP肯定离不开这两个组件了,因为手头上面在搞天气预报的app,用到了UICollectionView,也希望在这次的知识梳理的过程中不断深化知识,也发现新的问题。
      查看一下文档,在iOS6之后,多出来了UICollectionView,基本上和UITableView的API差不多,都需要设置DataSource和Delegate.
      在实际的使用中我们都会自定义我们自己的Cell。那我们先简单了解一下,结构。构成CollectionView分为3个结构:
    

    Cell 单元格 显示信息
    SupplementaryViews 页眉页脚
    Decoration Views 装饰整个View

      如果要实现CollectionView的话,基本需要实现`UICollectionViewDataSource`,`UICollectionViewDelegate`,`UICollectionViewDelegateFlowLayout`这三个协议,接下来就一一讲解一下。
    
      `UICollectionViewDataSource`:用于向Collection View提供数据,有以下方法:
    

    1.Section数目:

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
    

    2.Section里面有多少item

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    

    3.提供Cell设置

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    

    UICollectionViewDelegate:用于交互,有以下方法:
    1.管理cell的高亮

    optional func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool
    optional func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath)
    optional func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath)
    

    2.管理cell的选择

    optional func collectionView(_ collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) ->  Bool
    optional func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
    optional func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) ->  Bool
    

    UICollectionViewLayout进行排版,布局的作用
    1.定义每个UICollectionView 的大小

    optional func collectionView(_collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    

    2.定义每个UICollectionView 的 margin

    optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
    

    当你使用nib文件来设计Cell的时候,一定要记住的是,你对于他的样式都发生了改变,否则没必要使用nib文件,这也是我最近一直没搞懂什么时候使用nib文件,什么时候直接在 storyboard操作就可以了。

    相关文章

      网友评论

          本文标题:iOS UIKit之UICollectionView

          本文链接:https://www.haomeiwen.com/subject/xgszxttx.html