可以在通知内容扩展中使用 SwiftUI 视图吗? Xcode 模板只提供了一个视图控制器,可以这样做吗?
答案 0 :(得分:1)
是的,您应该能够使用 UIViewController
在 UIHostingController
中嵌入 SwiftUI 视图。这里有更广泛的答案 (Include SwiftUI views in existing UIKit application),但这里有一个使用 UNNotificationContentExtension
的 Xcode 模板作为基础的简短版本:
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var container: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let childView = UIHostingController(rootView: SwiftUIView())
addChild(childView)
childView.view.frame = container.bounds
container.addSubview(childView.view)
childView.didMove(toParent: self)
}
func didReceive(_ notification: UNNotification) {
//
}
}
答案 1 :(得分:0)
这是我如何使用 AutoLayout 规则做到的。
...
var hostingView: UIHostingController<NotificationView>!
...
func didReceive(_ notification: UNNotification) {
let notificationView = NotificationView()
hostingView = UIHostingController(rootView: notificationView)
self.view.addSubview(hostingView.view)
hostingView.view.translatesAutoresizingMaskIntoConstraints = false
hostingView.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
hostingView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
hostingView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
hostingView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
http://brunowernimont.me/howtos/2021-06-21-embed-swiftui-view-in-notification-content-extension