swift 類似高德地圖和58同城上下滑動view

ZY_FlyWay發表於2018-05-31


演示:




程式碼地址: https://github.com/RainManGO/PanView

主要在Xib中使用:xib的view直接繫結panview即可。如圖:



程式碼:

//
//  PanView.swift
//
//
//  Created by ZY on 2018/5/23.
//  Copyright © 2018年 zy. All rights reserved.
//

import UIKit

enum slideStates {
    case top
    case bottom
}

class PanView: UIView {
    
    var  panViewStates: slideStates = .bottom  //預設狀態是在底部
    var upPointY = 0.0   //最高值
    var middleY = 0.0  //滑動view 中間判定值
    var bottionY = 0.0  //最低值
    var currentY = 0.0   //當前的Y值
    
    let maxtop = 80.0
    
    override func awakeFromNib() {
        super.awakeFromNib()
        countY()
        addPanRecoginer()
        addTapRecoginer()
    }
}


//計算資料值
extension PanView {
    func countY(){
        upPointY = maxtop   //最高值
        middleY = Double(((self.superview?.frame.height)! - CGFloat(maxtop))/2)  //滑動view 中間判定值
        bottionY = Double(self.frame.minY)  //最低值
        currentY = bottionY
    }
    
}

//手勢
extension PanView {

    func addPanRecoginer(){
        let panRecoginer = UIPanGestureRecognizer.init(target: self, action: #selector(panHandle(pan:)))
        self.addGestureRecognizer(panRecoginer)
    }
    
    func addTapRecoginer(){
        let tapRecoginer = UITapGestureRecognizer.init(target: self, action: #selector(tapHandle(tap:)))
        self.addGestureRecognizer(tapRecoginer)
    }
    
}

//事件
extension PanView {
    
    @objc func panHandle(pan:UIPanGestureRecognizer){
        let  translation = pan.translation(in: self.superview)
        let  transY = Double(translation.y)
        
        if pan.state == .changed {
            if Double(self.frame.origin.y) < upPointY{
                currentY = upPointY
            }else if Double(self.frame.origin.y) > bottionY{
                currentY = bottionY
            }else{
                self.frame.origin.y = CGFloat(currentY + transY)
            }


        }else if pan.state == .ended {
            
            if (currentY + transY > upPointY) && (currentY + transY < middleY) { //如果當前位置在最上部和中線中間
                currentY = upPointY
            }else if (currentY + transY < bottionY) && (currentY + transY > middleY){
                currentY = bottionY
            }else if currentY + transY < upPointY{
                currentY = upPointY
            }else{
                currentY = bottionY
            }
            
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 10, initialSpringVelocity: 5, options: [], animations: {
                self.frame.origin.y = CGFloat(self.currentY)
            }) { (complete) in
                
            }
            
            currentY = Double(self.frame.origin.y)
        }
    
        
    }
    
    //待擴充套件tap
    @objc func tapHandle(tap:UITapGestureRecognizer){
    }
}

相關文章