0

我有一個包含多個圖像的集合視圖。我可以縮放單元格中的圖像,但我希望它和滾動視圖在輕按手勢時恢復到其原始大小。我的輕按手勢會將圖像恢復爲原始大小,但它不在屏幕上,滾動視圖仍保持縮放大小。這裏是我的代碼:UIScrollView如何在UIImageView縮放後恢復到原始大小

import UIKit 

class ZoomingCollectionViewCell: UICollectionViewCell, UIScrollViewDelegate { 

let zoomScrollView: UIScrollView = { 
    let scrollView = UIScrollView() 
    scrollView.backgroundColor = .white 
    scrollView.isUserInteractionEnabled = true 
    scrollView.translatesAutoresizingMaskIntoConstraints = false 
    scrollView.minimumZoomScale = 1.0 
    scrollView.maximumZoomScale = 6.0 
    scrollView.clipsToBounds = true 
    return scrollView 
}() 

var itemImageView: UIImageView = { 
    let imageView = UIImageView() 
    imageView.contentMode = .scaleAspectFit 
    imageView.translatesAutoresizingMaskIntoConstraints = false 
    imageView.backgroundColor = .white 
    imageView.isUserInteractionEnabled = true 
    return imageView 
}() 

var originalSize: CGRect! 

override init(frame: CGRect) { 
    super.init(frame: frame) 

    contentView.backgroundColor = .white 

    zoomScrollView.delegate = self 

    itemImageView.frame = CGRect(x: 0, y: 0, width: contentView.frame.size.width, height: contentView.frame.size.height) 

    zoomScrollView.frame = itemImageView.frame 

    originalSize = itemImageView.frame 

    let tap = UITapGestureRecognizer(target: self, action: #selector(tapZoomingGesture(_:))) 

    tap.numberOfTapsRequired = 2 

    zoomScrollView.addGestureRecognizer(tap) 

    zoomScrollView.addSubview(itemImageView) 

    contentView.addSubview(zoomScrollView) 
} 

func viewForZooming(in zoomScrollView: UIScrollView) -> UIView? { 

    return itemImageView 
} 

func tapZoomingGesture(_ sender: UIPinchGestureRecognizer) { 

    itemImageView.center = itemImageView.superview!.center 

    itemImageView.transform = .identity 

    zoomScrollView.frame = originalSize 
} 

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { 
    return true 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 
} 

回答

0

這適用於我。我只注意到我使用UIPinchGestureRecognizer作爲發件人,但由於某種原因,它仍然可以正常工作。

func tapZoomingGesture(_ sender: UIPinchGestureRecognizer) { 

    let newZoomScale: CGFloat = 1.0000001 

    let scrollViewSize = zoomScrollView.bounds.size 

    let w = (scrollViewSize.width/newZoomScale) 
    let h = (scrollViewSize.height/newZoomScale) 
    let x = w/6.0 
    let y = h/6.0 

    let rectToZoomTo = CGRect(x, y, w, h) 

    zoomScrollView.zoom(to: rectToZoomTo, animated: true) 

    zoomScrollView.frame = itemImageView.frame 

    itemImageView.center = zoomScrollView.center 

} 
相關問題