将UIPanGestureRecoginizer限制为边界迅速

问题描述 投票:0回答:1

我在uicollectionview单元中有一个水平滚动的图像,我想实现一个功能,例如facebook和photo app apple,单击图像,它覆盖了整个屏幕。您可以捏和平移图像,我想添加某些限制,例如facebook和photo应用程序,就像您捏照片时可以最大平移其宽度一样。

如果用户尝试将图像移出边界,我希望图像再次更新。我正在添加一些屏幕截图以提供有关它的想法。

现在,我正在使用简单的代码。

 guard gestureRecognizer.view != nil else {return}
    print(self.imgView.frame)
    if self.imgView.frame.size.width < (self.imgOrignal.width+100) {
        return
    }

    let piece = gestureRecognizer.view!
    // Get the changes in the X and Y directions relative to
    // the superview's coordinate space.
    let translation = gestureRecognizer.translation(in: piece.superview)
    if gestureRecognizer.state == .began {
        self.initialCenter = piece.center
    }
    // Update the position for the .began, .changed, and .ended states
    if gestureRecognizer.state != .cancelled {
        // Add the X and Y translation to the view's original position.
        let newCenter = CGPoint(x: initialCenter.x + translation.x, y: initialCenter.y + translation.y)
        piece.center = newCenter
    }
    else {
        // On cancellation, return the piece to its original location.
        piece.center = initialCenter
    }
}

enter image description herene

ios swift iphone uigesturerecognizer uipangesturerecognizer
1个回答
0
投票

我已经通过使用UIScrollView放大和缩小解决了这个问题,而不是使用捏和摇动手势,如果有人想实现该功能,我将在下面添加我的代码。

  func setZoomScale() {
    let widthScale = self.bgView.frame.size.width / self.imgView.bounds.width
    let heightScale = self.bgView.frame.size.height / self.imgView.bounds.height
    let minScale = min(widthScale, heightScale)
    self.imgScrollView.minimumZoomScale = minScale
    self.imgScrollView.zoomScale = minScale
}


extension YOUR CLASS: UIScrollViewDelegate {

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return self.imgView
}

func scrollViewDidZoom(_ scrollView: UIScrollView) {
    let imageViewSize = self.imgView.frame.size
    let scrollViewSize = scrollView.bounds.size
    let verticalInset = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
    let horizontalInset = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0
    scrollView.contentInset = UIEdgeInsets(top: verticalInset, left: horizontalInset, bottom: verticalInset, right: horizontalInset)
}

}

© www.soinside.com 2019 - 2024. All rights reserved.