使用swift 自定义的popView,从底部弹出view

在我们的项目中,我们经常会需要从控制器底部弹出一个View。有的人会去选择一个第三方的Demo,其实这个功能写起来还是蛮简单的。

直接上代码了。

import UIKit

class ZXPopView: UIView {
   
    var contenView:UIView?
    {
        didSet{
           setUpContent()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpContent(){
        
        if self.contenView != nil {
            self.contenView?.y = self.height
            self.addSubview(self.contenView!)
        }
        self.backgroundColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 0.4)
        self.isUserInteractionEnabled = true
        //为view添加手势。
        self.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(dismissView)))
        
    }
    
    
    @objc func dismissView(){
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { (true) in
           self.removeFromSuperview()
           self.contenView?.removeFromSuperview()
        }
    }
    func showInView(view:UIView){
        if (view == nil && contenView == nil) {
            return
        }
        
        view.addSubview(self)
       UIView.animate(withDuration: 0.3, animations: {
             self.alpha = 1.0
            self.contenView?.y = self.height-(self.contenView?.height)!
        }, completion: nil)
    }
//在Window上展示,当我们有的界面可能不能获取某个view上的时候,可以Window上展示contentView
    func showInWindow(){
        
        
        UIApplication.shared.keyWindow?.addSubview(self)
        
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 1.0
            self.contenView?.y = self.height-(self.contenView?.height)!
        }, completion: nil)
    }

}

其实原理很简单。自定义一个view,在view添加一个手势,利用这个手势来调用自己消失的方法。在view中放一个contentview。用来展示你要显示View,利用uiview动画,调整contenview的y值,来实现一个底部弹出效果,利用alfa值设置背景view的阴影效果。当然我们直接将我们自定义View直接添加要显示的父view中,当然也可以直接将自定义View添加到KeyWindow中。方法类似。

下面的代码是如何调用这个自定义的popView

 let popview = ZXPopView.init(frame: self.view.bounds)

       popview.contenView = UIView.init(frame: CGRect.init(x: 0, y: KScreenW - 100, width: KScreenW, height:100 ))

        popview.contenView?.backgroundColor = UIColor.orange

       popview.showInView(view: self.view)

我将继续完善这篇博客,代码后续会进一步的补齐。


你可能感兴趣的:(swift,iOS)