代码之家  ›  专栏  ›  技术社区  ›  King

防止滑动函数中的多重方法调用

  •  0
  • King  · 技术社区  · 7 年前

    我创建了一个滑块,该滑块从一条边移动到另一条边,拖动后返回到其原始位置。当它到达幻灯片的末尾时,我调用一个函数,但我现在面临的问题是,当它移动到末尾时,该函数被调用多次,应该只调用一次。我如何让这个滑块只调用一次而不是多次,因为如果用户决定在最后保持它不动,该方法将被重复调用。到目前为止,我的代码是bleow

    override func viewDidLoad() {
            super.viewDidLoad()
    
            let swipeGesture = UIPanGestureRecognizer(target: self, action: #selector(acknowledgeSwiped(sender:)))
            swipeImage.addGestureRecognizer(swipeGesture)
            swipeImage.isUserInteractionEnabled = true
            swipeGesture.delegate = self as? UIGestureRecognizerDelegate
        }
    var startingFrame: CGRect?
        @objc func acknowledgeSwiped(sender: UIPanGestureRecognizer) {
            if let sliderView = sender.view {
                let translation = sender.translation(in: swipeView)
                switch sender.state {
                case .began:
                    startingFrame = swipeImage.frame
                    fallthrough
                case .changed:
                    if let startFrame = startingFrame {
    
                        var movex = translation.x
                        if movex < -startFrame.origin.x { movex = -startFrame.origin.x }
    
                        let xMax = swipeView.frame.width - startFrame.origin.x - startFrame.width
                        if movex > xMax {
                            movex = xMax
                            acknowledgeTrip()
                        }
    
                        var movey = translation.y
                        if movey < -startFrame.origin.y { movey = -startFrame.origin.y }
    
                        let yMax = swipeView.frame.height - startFrame.origin.y - startFrame.height
                        if movey > yMax {
                            movey = yMax
    
                        }
    
                        sliderView.transform = CGAffineTransform(translationX: movex, y: movey)
                    }
                default: // .ended and others:
                    UIView.animate(withDuration: 0.1, animations: {
                        sliderView.transform = CGAffineTransform.identity
                    })
                }
            }
        }
    

    任何帮助都将不胜感激

    0 回复  |  直到 7 年前