- 初步配置:
- 在
Info.plist
文件中添加 UIApplicationSupports3DTouch
键,并将其值设为 YES
,表明应用支持 3D Touch。
- 关键类与方法:
- UIViewController 相关:
- 在包含 SwiftUI 视图的
UIViewController
子类中,需要覆盖 previewingContext(_:viewControllerForLocation:)
方法来提供预览视图控制器。例如:
extension UIViewController {
func registerForPreviewing(with view: UIView) {
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// 返回预览视图控制器实例
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let previewVC = storyboard.instantiateViewController(withIdentifier: "PreviewViewController") as? PreviewViewController else { return nil }
previewVC.configureForPreview()
previewingContext.sourceRect = CGRect(x: location.x, y: location.y, width: 1, height: 1)
return previewVC
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
// 处理从预览到完全打开视图的操作
show(viewControllerToCommit, sender: self)
}
}
- SwiftUI 相关:
- 对于 SwiftUI 视图,需要通过
UIViewControllerRepresentable
协议将其包装到 UIViewController
中,以便使用上述的 3D Touch 相关方法。例如:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, World!")
}
.onAppear {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let rootViewController = windowScene.windows.first?.rootViewController else { return }
rootViewController.registerForPreviewing(with: UIView())
}
}
}
- 相关视图设置:
- 对于希望支持 Peek and Pop 的视图,在
UIViewController
中,通过 registerForPreviewing(with:sourceView:)
方法注册源视图,该源视图即为用户按压触发 Peek and Pop 的视图。例如,在上述代码中,registerForPreviewing(with: self, sourceView: view)
中的 view
就是源视图。在 SwiftUI 中,可以在视图出现时(onAppear
修饰符)进行相关注册操作。