[英]Limit UIPanGestureRecognizer to boundaries swift
我在 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
}
}
我已經通過使用 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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.