swift仿微信下拉菜單menu

先放預覽結果圖:


image.gif

以及swift文件:


xcode

接下來直接貼代碼加注釋:MenuView.swift

import UIKit

//自定義的Delegate,用于處理menu的單擊事件回調
protocol SwiftNoDataShowViewDelegate  {
    func  didClickSelectedRow(index: Int,title: String,menu: MenuView)
}

class MenuView: UIView, UITableViewDelegate, UITableViewDataSource{

    //顯示在menu每一行的文字
    var titleArray : [String]?
    //記時器,負責顯示menu的動畫
    var timer: Timer?
    //記錄menu實際高度
    var resultFrame: CGRect?
    //menu內容用tableView顯示
    var tableView: UITableView?
    var menuDelegate: SwiftNoDataShowViewDelegate?
    
    init(frame: CGRect, titleArray: [String]) {
        //初始化高度為0,并保存實際高度用來做動畫
        super.init(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: 0))
        self.resultFrame = frame
        self.titleArray = titleArray
        self.backgroundColor = UIColor.white
       
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: .plain)
        tableView!.delegate = self
        tableView!.dataSource = self
        tableView!.isScrollEnabled = false
        tableView!.layer.masksToBounds = true
        tableView!.layer.cornerRadius = 6
        tableView!.backgroundColor = UIColor.darkGray
        tableView!.separatorStyle = .none
        self.addSubview(tableView!)

        //設置記時器每0.01秒觸發(fā)一次
        timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(animationStart), userInfo: nil, repeats: true)
        timer!.fire()
    }
    
    @objc func animationStart() {
        //每0.01秒高度增加1%,動畫時間為1秒
        let height = (resultFrame?.size.height)!/100.0
        self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height + height)
        //每次高度變化都要刷新視圖
        setNeedsDisplay()
        //到達實際高度后停止動畫
        if(self.frame.size.height >= (self.resultFrame?.size.height)!){
            timer!.invalidate()
        }
    }
    
    override func draw(_ rect: CGRect) {

        //繪制小三角形
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        let drawingRect = bounds
        let path = CGMutablePath()
        //設立設置的三角形在中間,具體位置可以自定
        path.move(to: CGPoint(x: drawingRect.width/2, y: 0))
        path.addLine(to: CGPoint(x: drawingRect.width/2-8, y: 8))
        path.addLine(to: CGPoint(x: drawingRect.width/2+8, y: 8))
        context.setFillColor(UIColor.black.cgColor)
        context.addPath(path)
        context.fillPath()
        //設置tableView的frame,用于動畫效果
        tableView?.frame = CGRect(x: 0, y: 8, width: frame.size.width, height: frame.size.height-8)
    }
    
    //menu item的數(shù)量
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (titleArray?.count)!
    }
    
    //headerview
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44))
        label.text = "HEADER"
        label.textColor = UIColor.blue
        label.textAlignment = .center
        let line = UIView(frame: CGRect(x: 0, y: 43.5, width: label.frame.size.width, height: 0.5))
        line.backgroundColor = UIColor.white
        label.addSubview(line)
        return label
    }
    //headerview高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    //顯示的cell,這里只顯示文字,具實際情況也可以加上圖片
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = "\(titleArray![indexPath.row])"
        cell.textLabel?.textColor = UIColor.white
        cell.textLabel?.font = UIFont.systemFont(ofSize: 12)
        cell.textLabel?.textAlignment = NSTextAlignment.left
        cell.backgroundColor = UIColor.clear
        let line = UIView(frame: CGRect(x: 0, y: 33.5, width: cell.frame.size.width, height: 0.5))
        line.backgroundColor = UIColor.white
        cell.addSubview(line)
        return cell
    }
    //單擊事件的Delegate回調
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        menuDelegate?.didClickSelectedRow(index: indexPath.row, title: self.titleArray![indexPath.row], menu: self)
    }
    //cell的高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 35
    }
    //移除menu的動畫,透明度漸變效果
    func removeMenu(){
        UIView.animate(withDuration: 1, animations: {
            self.alpha = 0
        }) { (finish) in
            self.removeFromSuperview()
        }
    }
    
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

MenuViewController.swift

import UIKit

class MenuViewController: UIViewController,SwiftNoDataShowViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        let btn = UIButton(frame: CGRect(x: 100, y: 70, width: 150, height: 50))
        btn.setTitle("menu", for: .normal)
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.blue.cgColor
        btn.addTarget(self, action: #selector(add(_:)), for: .touchUpInside)
        view.addSubview(btn)
        
    }
    
    @objc func add(_ btn: UIButton) {
        //創(chuàng)建menuView
        let titleArray = ["title1","title2","title3","title4","title5","title6"]
        let menuView = MenuView(frame: CGRect(x: 50, y: 120, width: 250, height: titleArray.count*35+44+8), titleArray: titleArray)
        menuView.menuDelegate = self
        self.view.addSubview(menuView)
    }
    //單擊item的代理回調
    func didClickSelectedRow(index: Int, title: String, menu: MenuView) {
        print("\(index)----\(title)")
        menu.removeMenu()
    }

}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容