Can a SwiftUI view be used in a Notification Content Extension? The Xcode template only offers a view controller, could this be done?
Yes, you should be able to embed a SwiftUI view in the UIViewController
using UIHostingController
. There are more extensive answers here ( Include SwiftUI views in existing UIKit application ), but here's a short version using the Xcode template for UNNotificationContentExtension
as a base:
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) {
//
}
}
Here's how I do it using AutoLayout rules.
...
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.