XZ_iOS 按钮的吸附效果实现

我们需要实现的是左侧的吸附效果,效果图如下:

实现代码:


let XZScreenWidth = UIScreen.main.bounds.size.width
let XZScreenHeight = UIScreen.main.bounds.size.height

// 是否是iphone X
let isIphoneX = XZScreenHeight >= 812 ? true : false
// navigationBarHeight
let navigationBarHeight : CGFloat = isIphoneX ? 88 : 64
// tabBarHeight
let tabBarHeight : CGFloat = isIphoneX ? 49 + 34 : 49

class XZCartViewController: UIViewController {
    
    private let button = UIButton(type: .custom)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ///
        button.frame = CGRect(x: 0, y: view.frame.size.height * 1 / 3.0, width: 60, height: 60)
        
        button.setImage(UIImage(named: "可爱的小姑娘"), for: .normal)
        button.layer.cornerRadius = 30
        button.layer.masksToBounds = true
        view.addSubview(button)
        
        button.addTarget(self, action: #selector(addEvent), for: .touchUpInside)
        
        /// 添加手势
        let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(recognizer:)))
        panRecognizer.minimumNumberOfTouches = 1
        panRecognizer.isEnabled = true
        panRecognizer.delaysTouchesEnded = true
        panRecognizer.cancelsTouchesInView = true
        
        button.addGestureRecognizer(panRecognizer)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        button.frame.origin.x = 0
        button.frame.origin.y = navigationBarHeight
    }
    
    /// 手势事件
    @objc func handlePanGesture(recognizer: UIPanGestureRecognizer) {
        
        // 移动状态
        let recstate = recognizer.state
        
        switch recstate {
        case .began:
            break
        case .changed:
            
            let translation = recognizer.location(in: view)
            recognizer.view?.center = translation
            break
        case .ended:
            let end = recognizer.location(in: view)
            
            let minX: CGFloat = 0
            let minY = navigationBarHeight
            let maxY = XZScreenHeight - tabBarHeight - 60
        
            var currentY = end.y

            if currentY <= minY {
                currentY = minY
            }else if currentY >= maxY {
                currentY = maxY
            }

            print("currentY:", currentY, "maxY:", maxY)
            
            UIView.animate(withDuration: 0.5) {
                recognizer.view?.frame.origin.x = minX
                recognizer.view?.frame.origin.y = currentY
            }
  
            break
        default:
            break
        }
        
    }
    
    /// 点击事件
    @objc func addEvent() {
        
        print("触发点击事件")
    }

}
发布了208 篇原创文章 · 获赞 52 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/understand_XZ/article/details/90718992