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, commitviewControllerToCommit: 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下载


本文由 Harvey 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论