我正在开发一个应用程序,通过使用UIScrollView
展示UIImages
的画廊。我的问题是如何实现单击进行缩放
,双击进行缩小
,在处理UIScrollView
时该如何操作。
我正在开发一个应用程序,通过使用UIScrollView
展示UIImages
的画廊。我的问题是如何实现单击进行缩放
,双击进行缩小
,在处理UIScrollView
时该如何操作。
你需要在你的视图控制器中实现UITapGestureRecognizer - 文档 在这里 -
- (void)viewDidLoad
{
[super viewDidLoad];
// what object is going to handle the gesture when it gets recognised ?
// the argument for tap is the gesture that caused this message to be sent
UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnce:)];
UITapGestureRecognizer *tapTwice = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwice:)];
// set number of taps required
tapOnce.numberOfTapsRequired = 1;
tapTwice.numberOfTapsRequired = 2;
// stops tapOnce from overriding tapTwice
[tapOnce requireGestureRecognizerToFail:tapTwice];
// now add the gesture recogniser to a view
// this will be the view that recognises the gesture
[self.view addGestureRecognizer:tapOnce];
[self.view addGestureRecognizer:tapTwice];
}
基本上这段代码的意思是,当在self.view
中注册了一个UITapGesture
时,方法tapOnce或tapTwice将在self
中被调用,具体取决于它是单击还是双击。因此,您需要将这些点击方法添加到您的UIViewController
中:
- (void)tapOnce:(UIGestureRecognizer *)gesture
{
//on a single tap, call zoomToRect in UIScrollView
[self.myScrollView zoomToRect:rectToZoomInTo animated:NO];
}
- (void)tapTwice:(UIGestureRecognizer *)gesture
{
//on a double tap, call zoomToRect in UIScrollView
[self.myScrollView zoomToRect:rectToZoomOutTo animated:NO];
}
Swift 4.0 版本可以在双击时实现两倍缩放。
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
在某个地方(通常是在viewDidLoad方法中):
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onDoubleTap(gestureRecognizer:)))
tapRecognizer.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(tapRecognizer)
处理程序:
@objc func onDoubleTap(gestureRecognizer: UITapGestureRecognizer) {
let scale = min(scrollView.zoomScale * 2, scrollView.maximumZoomScale)
if scale != scrollView.zoomScale {
let point = gestureRecognizer.location(in: imageView)
let scrollSize = scrollView.frame.size
let size = CGSize(width: scrollSize.width / scale,
height: scrollSize.height / scale)
let origin = CGPoint(x: point.x - size.width / 2,
y: point.y - size.height / 2)
scrollView.zoom(to:CGRect(origin: origin, size: size), animated: true)
print(CGRect(origin: origin, size: size))
}
}
scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
。 - Neph