如何在iOS中点击缩放和双击缩小?

时间:2012-01-25 19:27:51

标签: ios objective-c uiscrollview uitapgesturerecognizer

我正在开发一个应用程序,使用UIImages显示UIScrollView的图库,我的问题是,如何点按zoom并点击zoom out,使用UIScrollView处理时如何工作。

2 个答案:

答案 0 :(得分:39)

您需要在viewController中实现UITapGestureRecognizer - docs here

- (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];

}

基本上,此代码表示当在UITapGesture中注册self.view时,将在{{1}中调用方法 tapOnce tapTwice 取决于它是单击还是双击。因此,您需要将这些点击方法添加到self

UIViewController

希望有所帮助

答案 1 :(得分:2)

Swift 3.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)

处理程序:

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