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")
}
}