将 UIPanGestureRecognizer 快速限制为边界
Posted
技术标签:
【中文标题】将 UIPanGestureRecognizer 快速限制为边界【英文标题】:Limit UIPanGestureRecognizer to boundaries swift 【发布时间】:2019-11-03 16:40:53 【问题描述】:我在 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
【问题讨论】:
【参考方案1】:我已经通过使用 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)
【讨论】:
以上是关于将 UIPanGestureRecognizer 快速限制为边界的主要内容,如果未能解决你的问题,请参考以下文章
将 UIPanGestureRecognizer 速度添加到 UIViewPropertyAnimator
将 UIPanGestureRecognizer 快速限制为边界
使用 UIPanGestureRecognizer 时如何将超级视图与视图一起居中?
需要在 iOS 中使用 UIPanGestureRecognizer 将 UIImageView 的移动限制在 UITableView 覆盖的区域