Swift:如何为CALayer启用缩放功能? [英] Swift: How to enable pinch-to-zoom for CALayer?

查看:190
本文介绍了Swift:如何为CALayer启用缩放功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试滚动和缩放多个多边形路径的CALayer,特别是CAShapeLayer。我将CALayer添加到了UIScrollView中,该UIScrollView已成功启用了在CALayer上滚动。

I have been trying to scroll and zoom a CALayer, specifically a CAShapeLayer, of several polygon paths. I added the CALayer to a UIScrollView which has successfully enabled scrolling around the CALayer.

但是,缩小缩放不起作用。一些教程已经实现了使用UIScrollViewDelegate缩放UIImageView的方法,基本上是这样的:

However, pinch to zoom is not working. Several tutorials have implemented zooming a UIImageView with the UIScrollViewDelegate essentially like so:

@IBOutlet var scrollView : UIScrollView!
var imageView = UIImageView()
scrollView.addSubview(imageView)

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return imageView
}

但是CALayer与UIView不兼容,我有找不到关于调和差异的信息。

But CALayer is incompatible with UIView and I have found no information on reconciling the difference.

在Swift中,有没有类似的本地方法来缩放CALayer?逃避我的事情真的很简单吗?任何帮助,将不胜感激;

Is there a similar native way to zoom a CALayer in Swift? Is it something really simple that escaped me? Any help would be appreciated; apologies if I am missing the obvious.

推荐答案

经过大量挖掘后,我发现相关的 Apple的文档 。事实证明,如果设置正确,则在CALayers上会自动处理捏缩放。我为Swift修改了演示代码,并提出了适用于我的基本结构。

After much digging I found the related documentation from Apple. Turns out pinch-to-zoom is handled automatically on CALayers if they are set up correctly. I adapted the demo code for Swift and came up with this basic structure, which worked for me.

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet var scrollView : UIScrollView!
    var layerView = UIView()
    var shapeLayer= CAShapeLayer()

    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return layerView // Specify the layer to scroll, cannot be the UIScrollView used for scrolling
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {
        // This was noted as required but no inner code is necessary
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        layerView.layer.addSublayer(shapeLayer) // Attach layer to the canvas view
        scrollView.addSubview(layerView) // Attach the views
        // ... Add layer content, set max and min scaling values as well as layer/view sizes to encompass content
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

我希望这对其他人有帮助!

I hope this helps someone else!

这篇关于Swift:如何为CALayer启用缩放功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆