博客> Peek和Pop功能开发(3D Touch开发之一)
Peek和Pop功能开发(3D Touch开发之一)
2018-11-09 18:15 评论:0 阅读:182 yao7778899
iOS开发 Pop 3dtouch peek

1、哪些设备支持3D Touch

iPhone 6s/Plus、iPhone 7s/Plus、iPhone 8s/Plus、iPhone X (系统必须是iOS9或者更新的版本)

2、怎么实现Peek和Pop功能

要实现Peek和Pop,必须实现UIViewControllerPreviewingDelegate,此协议只有两个接口

1)Peek接口

 public func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController?

2)Pop接口

  public func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController)

实现UIViewControllerPreviewingDelegate协议示例代码

 extension ViewController: UIViewControllerPreviewingDelegate {

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {

        guard let sorce = storyboard?.instantiateViewController(withIdentifier: "GameViewController") else {

            return nil;
        }

        // Peek弹出窗口的Size
        sorce.preferredContentSize = CGSize(width: 0.0, height: 500) 
        // 预览区域(你所按位置附近一块区域)
        previewingContext.sourceRect = CGRect(x: 0, y: location.y - 100, width: view.bounds.size.width, height: 100)

        print("Peek")
        return sorce
    }

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {

        show(viewControllerToCommit, sender: self);
        print("Pop")
    }
    }

此外还需要注册一个视图来响应3D Touch操作

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        if traitCollection.forceTouchCapability == .available {

            // 注册一个View来响应 3D Touch操作(Peek Or Pop)
            registerForPreviewing(with: self, sourceView: view)
            print("你的设备支持3D Touch")
        }
    }

3、Demo下载

PeekAndPop

更多更详细教程请访问个人站点: 码出一个长城

收藏
0
sina weixin mail 回到顶部