Swift类似美团下拉菜单

写在前面

好久没有写文章记录总结平时用到的知识了,最近都在准备新项目的,项目上手才发现,自己可能真的是该再多努力一些了,今天记录的这个是项目里面用到的一个控件,我之前有在网上找过,看看有没有类似的demo,然而,哈哈哈,并没有找到合适的,大体效果就是美团 APP 上那种,如图:

![meituanPic2.PNG](http://upload-images.jianshu.io/upload_images/668737-59683ee4d20bd3f2.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

我好像就在美团上看见了这种类似的效果,然后公司项目要用到类似控件,于是就自己写了一个放在这里吧,嘿嘿

步入正题

接下来不如正题,控件效果是这样的-----------> 图:

DOP_Screen.gif

大体效果大致就是像 GIF 图上显示的这样,这只是个简单的大体 demo,具体的细化还没有做呢,里面的数据也是我随意填的,😜。

大体思路

这个控件的功能也很明显了,分左中右这三块,大概说一下这个控件的大体思路,从左往右,最左边是 为了增加点儿视觉效果,而且选项不多,所以用的图片多点儿,我是用的 collectionView , 里面的 cell 就特别简单了,就是一个 ImageView+label 搞定的。中间需要复选,这个是用了两个tableView,将两个tableView进行关联。最右边是一个简单的tableView 。这两块里用的 tableView 里面的 cell 就是用的系统自带的 cell 样式。这个控件我就是根据 tableView的思想来 code 的,外部方法的调用也都是通过dataSourcedelegate来调用的。大体介绍完毕,接下来就结合代码介绍一下。

代码

第一部分:提前工作准备
//MARK:- 全局变量
public let kTableViewCellHeight: Int = 43
public let kCollectionViewCellHeight: Int = 100
public let kCollectionViewHeight: Int = 220
public let kTableViewHeight: Int = 300
public let kButtomImageViewHeight: Int = 21

public let kTextColor: UIColor = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1)
public let kDetailTextColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
public let kSepatatorColor: UIColor = UIColor(red: 219/255.0, green: 219/255.0, blue: 219/255.0, alpha: 1)
public let kCellBgColor: UIColor = UIColor(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1)
public let kTextSelectColor: UIColor = UIColor(red: 253/255.0, green: 191/255.0, blue: 44/255.0, alpha: 1)```
这个没有什么可以介绍的,我就是比较喜欢把可能用到的变量写在前面,便于修改啊什么的。
######第二部分:DOPIndexPath

//MARK:DOPIndexPath
class DOPIndexPath: NSObject {
var column:Int?
var row:Int?
var item:Int?

init(dopColumn: Int, dopRow: Int) {
    column = dopColumn
    row = dopRow
    item = -1
}

convenience init(dopColumn: Int, dopRow: Int, dopItem: Int) {
    self.init(dopColumn: dopColumn, dopRow: dopRow)
    item = dopItem
}

static func indexPathWith(col: Int, row: Int) -> DOPIndexPath {
    let indexPath = DOPIndexPath.init(dopColumn: col, dopRow: row)
    return indexPath
}

static func indexPathWith(col: Int, row: Int, item: Int) -> DOPIndexPath {
    return DOPIndexPath(dopColumn: col, dopRow: row, dopItem: item)
}

}

这个就是根据```tableView```的思路,声明了一个``` IndexPath ```类,这里的 ```column```是用来区分 titleBar 上是第几列的
![titleBar.png](http://upload-images.jianshu.io/upload_images/668737-a97b01199641dd71.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
```row``` 就是控件中的```tableView```中```cell```的行数,```item```是中间双```tableView```中右边```rightTableView```中```cell```用的。
看着这些方法是不是很熟悉啊,就是 ```tableView ``` 中我们经常用到的方法。😁

######DOPDropDownMenuDataSource+DOPDropDownMenuDelegate

//MARK:DOPDropDownMenuDataSource
@objc protocol DOPDropDownMenuDataSource : NSObjectProtocol {
//返回 menu 第column列有多少行
func menu(dopMenu menu: DOPDropDownMenu, numberOfRowsInColumn column: Int) -> Int

//返回 menu 第column列 每行title
func menu(dopMenu menu: DOPDropDownMenu, titleForRowAtIndexPath indexPath: DOPIndexPath) -> String

//返回 menu 有多少列, 默认1列
func numberOfColumnsInMenu(dopMenu menu: DOPDropDownMenu) -> Int

//新增 返回 menu 第column列 每行image
@objc optional func menu(dopMenu menu: DOPDropDownMenu, imageNameForRowAtIndexPath indexPath: DOPIndexPath) -> String

//新增 detailText, right text
@objc optional func menu(dopMenu menu: DOPDropDownMenu, detailTextForRowAtIndexPath indexPath: DOPIndexPath) -> String

//新增 当有column列 row行 返回有多少个item, 如果>0, 说明有二级列表, =0 没有二级列表
@objc optional func menu(dopMenu menu: DOPDropDownMenu, numberOfItemsInRow row:Int, column: Int) -> Int

//新增 当有column列 row行 item项 title 如果都没有可以不实现该协议
@objc optional func menu(dopMenu menu: DOPDropDownMenu, titleForItemsInRowAtIndexPath indexPath: DOPIndexPath) -> String

//新增 当有column列 row行 item项 image
@objc optional func menu(dopMenu menu: DOPDropDownMenu, imageNameForItemsInRowAtIndexPath indexPath: DOPIndexPath) -> String
//新增 当有column列 row行 item项 title
@objc optional func menu(dopMenu menu: DOPDropDownMenu, detailTextForItemsInRowAtIndexPath indexPath: DOPIndexPath) -> String

}
//MARK:-DOPDropDownMenuDelegate
@objc protocol DOPDropDownMenuDelegate : NSObjectProtocol {

//点击代理, 点击了第column 第row 或者item项, 如果item >= 0
@objc optional func menu(_ menu: DOPDropDownMenu, didSelectRowAtIndexPath indexPath: DOPIndexPath) -> Void
//
@objc optional func menu(_ menu: DOPDropDownMenu, willSelectRowAtIndexPath indexPath: DOPIndexPath) -> IndexPath

}

这一部分是声明的 protocol, 便于在外部调用,每个方法都有注释了,里面的方法和```tableView ```也是很相似。

######DOPBackgroundCellView

//MARK:DOPBackgroundCellView
class DOPBackgroundCellView:UIView {

override func draw(_ rect: CGRect) {
    //Drawing code
    let context: CGContext = UIGraphicsGetCurrentContext()!
    //画一条底部线
    context.setStrokeColor(red: 219.0/255, green: 224.0/255, blue: 228.0/255, alpha: 1);//线条颜色
    context.move(to: CGPoint(x: 0, y: 0))
    context.addLine(to: CGPoint(x: rect.size.width, y: 0))
    context.move(to: CGPoint(x: 0, y: rect.size.height))
    context.addLine(to: CGPoint(x: rect.size.width, y: rect.size.height))
    context.strokePath()
}

}

这个是用 context 画的一个 cell 选中的背景 view,当然也可以用别的代替啊
######DataSourceFlags

struct dataSourceFlags {

var numberOfRowsInColumn : Int = 1
var numberOfItemsInRow : Int = 1
var titleForRowAtIndexPath : Int = 1
var titleForItemsInRowAtIndexPath : Int = 1
var imageNameForRowAtIndexPath : Int = 1
var imageNameForItemsInRowAtIndexPath : Int = 1
var detailTextForRowAtIndexPath : Int = 1
var detailTextForItemsInRowAtIndexPath : Int = 1

}

这个是声明的一个结构体,里面存放的是每个 protocol 返回的 Num,以便在本体里进行判断操作。名字和 protocol 的方法名相同。

######DOPDropDownMenu

//MARK:DOPDropDownMenu

这一部分代码比较多,先说控件上所有的 title,image 都是用自定义的动画实现的。主要有以下几个方法:

fileprivate func animateIndicator(indicator: CAShapeLayer, forward:Bool, complete:()->()) -> Void

animateBackGroundView

fileprivate func animateBackGroundView(view: UIView, show: Bool, complete:()->()) -> Void

fileprivate func animateCollectionView(collectionView: UICollectionView, show: Bool, complete:()->()) -> Void

fileprivate func animateTableView(tableView: UITableView?, show: Bool, complete:()->()) -> Void

fileprivate func animateTitle(title: CATextLayer, show: Bool, complete: ()->()) -> Void

fileprivate func animateIdicator(indicator: CAShapeLayer, background:UIView, tableview: UITableView, title: CATextLayer, forward: Bool, complete:()->()) -> Void

fileprivate func animateCollectionIdicator(indicator: CAShapeLayer, background:UIView, collectionView: UICollectionView, title: CATextLayer, forward: Bool, complete:()->()) -> Void

方法中包含了```title```,```indicator```,```BackGroundView```,```tableVIew```,```collectionView```改变效果的实现.动画中的方法基本都是关联的,我将它们拆分开,以便复用,每个方法中也比较多的frame 变换计算。

在前面说过了,这个控件是由```collectionView```和```tableView```构成的, 在init 方法中初始化```collectionView```、```tableView```、```bottomImageView ```(底部的条)、``` navBar``` 的``` tapGesture```(手势),```backgroundTapGesture```(点击背景消失手势)、、、
在 ```dataSource ```的 set 方法中给结构体中的```structDataSourceFlags```各项复0和1值,便于接下来的往外传代理方法时候进行判断。

structDataSourceFlags.numberOfRowsInColumn = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:numberOfRowsInColumn:))))! ? 1 : 0
structDataSourceFlags.numberOfItemsInRow = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:numberOfItemsInRow:column:))))! ? 1 : 0
structDataSourceFlags.titleForRowAtIndexPath = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:titleForRowAtIndexPath:))))! ? 1 : 0
structDataSourceFlags.titleForItemsInRowAtIndexPath = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:titleForItemsInRowAtIndexPath:))))! ? 1 : 0
structDataSourceFlags.imageNameForRowAtIndexPath = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:imageNameForRowAtIndexPath:))))! ? 1 : 0
structDataSourceFlags.imageNameForItemsInRowAtIndexPath = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:imageNameForItemsInRowAtIndexPath:))))! ? 1 : 0
structDataSourceFlags.detailTextForRowAtIndexPath = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:detailTextForRowAtIndexPath:))))! ? 1 : 0
structDataSourceFlags.detailTextForItemsInRowAtIndexPath = (self.dataSource?.responds(to: #selector(DOPDropDownMenuDataSource.menu(dopMenu:detailTextForItemsInRowAtIndexPath:))))! ? 1 : 0

然后就是 ```nav```的构建。包括:title,separator,Indicators 表现在控件上就是,navBar 上的题目,分割线,和上下的指示条(这里指示条有 bug,我还没有找出来,想着后期用 ImgView 替代)根据传入的 navBar 上 title 的数目和 column 数量进行构建 navBar,并将 title,separator,Indicators放进数组里面储存,以便进行操作(比如点击某个选项后 title 改变)。
接下来说的就是 navBar 上的点击事件的响应了,由于最左边的是```collectionView``` 和其余两个不一样(其余两个是 tableView)所以在处理点击方法时候需要判断是不是 column 的 tapIndex == 0? 和 所选的 view 是否是打开的 isShow? ,一共四种大情况,还需要再判读 collectionView的状态进行 show OR close。

if tapIndex == 0 && isShow {
if (self.superview?.subviews.contains(self.leftTableView))! || (self.superview?.subviews.contains(self.rightTableView))! {
self.animateIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, tableview: self.leftTableView, title: titles[currentSelectedMenudIndex], forward: false, complete: {
isShow = false
})
} else {

        }
        self.animateCollectionIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, collectionView: self.collectionView!, title: titles[currentSelectedMenudIndex], forward: false, complete: {
            currentSelectedMenudIndex = tapIndex
            isShow = false
        })
    } else if tapIndex == 0 && !isShow {
        currentSelectedMenudIndex = tapIndex
        //            self.collectionView?.reloadData()
        self.animateCollectionIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, collectionView: self.collectionView!, title: titles[currentSelectedMenudIndex], forward: true, complete: {
            currentSelectedMenudIndex = tapIndex
            isShow = true
        })
    }
    
    if isShow && tapIndex != 0{
        
        if (self.superview?.subviews.contains(self.collectionView!))! {
            self.animateCollectionIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, collectionView: self.collectionView!, title: titles[currentSelectedMenudIndex], forward: false, complete: {
                currentSelectedMenudIndex = tapIndex
                isShow = false
            })
        } else {
            
        }
        self.animateIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, tableview: self.leftTableView, title: titles[currentSelectedMenudIndex], forward: false, complete: {
            currentSelectedMenudIndex = tapIndex
            isShow = false
        })
    } else if tapIndex != 0 && !isShow{
        currentSelectedMenudIndex = tapIndex
        
        self.leftTableView.reloadData()
        if (dataSource != nil) && structDataSourceFlags.numberOfItemsInRow != 0 {
            //                    self.rightTableView.reloadData()
        }
        self.animateIdicator(indicator: indicators[tapIndex], background: backGroundView, tableview: self.leftTableView, title: titles[tapIndex], forward: true, complete: {
            isShow = true
        })
    }
处理完 navBar 上的点击事件然后就是 ```backGroundView``` 的点击事件方法了:

@objc fileprivate func backGroundTapped(paramSender: UITapGestureRecognizer) -> Void {
if (self.superview?.subviews.contains(collectionView!))! {
self.animateCollectionIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, collectionView: self.collectionView!, title: titles[currentSelectedMenudIndex], forward: false, complete: {
isShow = false
})
} else {
self.animateIdicator(indicator: indicators[currentSelectedMenudIndex], background: backGroundView, tableview: self.leftTableView, title: titles[currentSelectedMenudIndex], forward: false) {
isShow = false
}
}
}

然后就是 ```tableView```和```collectionView```的代理方法了,这里的 ```tableView```用了 两个,用来区分显示一个还是显示两个就是用到 item 是否有数据来判断。

######使用

dopMenu = DOPDropDownMenu(origin: CGPoint(x: 0, y: 64), height: 44)
dopMenu.dataSource = self
dopMenu.delegate = self
self.view.addSubview(dopMenu)

控件的初始化就特别简单了,设置好```frame``` 声明```delegate```和```dataSource```是self,就好了
 控件中赋值和响应方法是通过代理方法调用的:
delegate:

//MARK:- delegate
func numberOfColumnsInMenu(dopMenu menu: DOPDropDownMenu) -> Int {
return 3
}

func menu(dopMenu menu: DOPDropDownMenu, numberOfRowsInColumn column: Int) -> Int {
    if column == 0 {
        return allSorts.count
    } else if column == 1 {
        return sifts.count
    } else {
        return sorts.count
    }
}

func menu(dopMenu menu: DOPDropDownMenu, titleForRowAtIndexPath indexPath: DOPIndexPath) -> String {
    if indexPath.column == 0 {
        return allSorts[indexPath.row!]
    } else if indexPath.column == 1 {
        return sifts[indexPath.row!]
    } else {
        return sorts[indexPath.row!]
    }
}
dataSource:

//new datasource
func menu(dopMenu menu: DOPDropDownMenu, imageNameForRowAtIndexPath indexPath: DOPIndexPath) -> String {
if indexPath.column == 0 || indexPath.column == 1 {
if let num = indexPath.row {
return "ic_filter_category_(num)"
}

    }
    return ""
}

func menu(dopMenu menu: DOPDropDownMenu, imageNameForItemsInRowAtIndexPath indexPath: DOPIndexPath) -> String {
    if indexPath.column == 0 && indexPath.item! >= 0 {
        if let num = indexPath.row {
            return "ic_filter_category_\(num)"
        }
    }
    return ""
}

func menu(dopMenu menu: DOPDropDownMenu, detailTextForRowAtIndexPath indexPath: DOPIndexPath) -> String {
    if indexPath.column! < 3 {
        return String(arc4random()/1000)
    }
    return "00"
}

func menu(dopMenu menu: DOPDropDownMenu, detailTextForItemsInRowAtIndexPath indexPath: DOPIndexPath) -> String {
    return String(arc4random()/1000)
}

func menu(dopMenu menu: DOPDropDownMenu, numberOfItemsInRow row: Int, column: Int) -> Int {
    if column == 1 {
        if row == 0 {
            return cates.count
        } else if row == 1 {
            return movices.count
        } else if row == 2 {
            return hotels.count
        }
    }
    return 0
}

func menu(dopMenu menu: DOPDropDownMenu, titleForItemsInRowAtIndexPath indexPath: DOPIndexPath) -> String {
    if indexPath.column == 1 {
        if indexPath.row == 0 {
            return cates[indexPath.item!]
        } else if indexPath.row == 1 {
            return movices[indexPath.item!]
        } else if indexPath.row == 2 {
            return hotels[indexPath.item!]
        }
    }
    return "没有"
}

func menu(_ menu: DOPDropDownMenu, didSelectRowAtIndexPath indexPath: DOPIndexPath) {
    if indexPath.item! > 0 {
        print("点击了第\(indexPath.column)列 - 第\(indexPath.row)行 - 第\(indexPath.item)项")
    } else {
        print("点击了第\(indexPath.column)列 - 第\(indexPath.row)行")
    }
}

使用方法就和我们平时用的 tableView类似,就是根据column,row,item进行操作

#####总结
项目大致流程就是这样子,代码有点儿多了,也不能具体拿出来分析了,里面各种方法穿插使用,可能会晕,具体的方法使用还是看代码的,自己回经常回头看的,这篇文章也会多多弥补缺漏的。。。。

代码链接在这:https://github.com/irembeu/SwiftDropDownMenuDemo
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容