ios - 快速将 UIPanGestureRecognizer 限制为边界

标签 ios swift iphone uigesturerecognizer uipangesturerecognizer

我在 uicollectionview 单元格内有一个水平滚动的图像,我想实现像 facebook 和照片应用程序苹果这样的功能,您单击图像,它会覆盖整个屏幕。你可以捏和平移图像,我想添加一些限制,就像 Facebook 和照片应用程序一样,比如当你捏图片时,你可以最大程度地平移到其宽度。

如果用户尝试将图像移出边界,我希望图像再次居中。我添加了一些屏幕截图来提供有关它的想法。

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

 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 here ne

最佳答案

我已经通过使用 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)
}

}

关于ios - 快速将 UIPanGestureRecognizer 限制为边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682338/

相关文章:

ios - 使用 UITableView Cell 中的 segue 更新数据

iOS WebRTC 处理丢包

iphone - UIButton 事件 'Touch Up Inside' 不起作用。 'Touch Down' 工作正常

ios - 在sqlite数据库中插入多个表数据

macos - NSTextField 可调整大小以适合内容

iphone - sqlite3 更新在 ios 中不起作用

ios - 帐户存储错误 5

ios - NSMutableArray replaceObjectAtIndex :withObject Loop Leakage

ios - 如何在同一个iOS项目中使用多个Icomoon字体?

ios - Swift 4 页面控制观察者