iOS切换标签组件 FlexPageView

2019-03-18  本文已影响0人  亲爱的八路

先看要实现的效果

1552911813695.gif
使用例子直接看demo https://github.com/nullLuli/FlexPageView
下面说说FlexPageView构成

FlexPageView是像UITableView一样的控件,处理基础操作,并把数据源和UI留给外部定制。

FlexPageView 主要处理的事情:

FlexPageView由两部分组成,上方的菜单栏叫做FlexMenuView,下方内容叫 PageContentView

FlexMenuView

menu view考虑到以后的UI定制,比如在title上加个最新、最热、小红点之类的需求,采用了UICollectionView,这样可以自己在FlexPageView外面写cell和layout。既然要支持UI定制,数据源也需要支持定制。于是我定义了menuview cell样式协议、数据源协议、layout协议,如下所示

//menu view cell 协议
public protocol IMenuViewCell {

    func updateScrollingUI(with precent: CGFloat)

    func updateSelectUI()

    func setData(data: IMenuViewCellData, option: FlexPageViewOption)

}

// cell 数据源协议
public protocol IMenuViewCellData {

    var CellClass: UICollectionViewCell.Type { get }
    
    var identifier: String { get }
}

// layout 协议
open class MenuViewBaseLayout: UICollectionViewLayout {
    public weak var delegate: MenuViewLayoutProtocol?
}

public protocol MenuViewLayoutProtocol: class {
    func collectionView(_ collectionView: UICollectionView, dataForItemAtIndexPath indexPath: IndexPath) -> Any
}

FlexMenuView通过reloadTitles方法载入数据,然后在cellForItemAt方法中使用数据源(IMenuViewCellData)中的CellClass和identifier给 FlexMenuView提供cell类型和复用ID,cell通过IMenuViewCell协议方法setData接受data的赋值;FlexMenuView是一个 UICollectionView ,通过自定义的layout计算cell位置和尺寸,layout是可以在FlexPageView外部重写的,layout中有个delegate可以用来从FlexMenuView中获取每个cell的数据,以此来计算每个cell的size

这样的设计可以支持多种data、cell类型

PageContentView

page content view需要支持左右滑动,所以就用了一个简单的scrollview来实现。在scrollview滚动的代理方法scrollViewDidScroll中更新menuview的动画,在scrollViewDidEndDragging或者scrollViewDidEndDecelerating中调用constructPages进行页面生成、销毁、断页。

需要注意的是,目前预加载是在缓存整理前面的,所以如果预加载范围比缓存范围大,随即就会以不在缓存中为由释放页面

上一篇下一篇

猜你喜欢

热点阅读