1. SwiftUI in UIView
Here is my MessagesViewController:
import UIKit
import Messages
class MessagesViewController: MSMessagesAppViewController {
let swiftUIView = MainView()
override func viewDidLoad() {
super.viewDidLoad()
addSubSwiftUIView(swiftUIView, to: view)
}
}
The code is simple because the magic is being done by the boilerplate in the UIViewController extension bellow. Got the the idea and code from the article 'Getting started with UIKit in SwiftUI and vice versa' by Antoine van der Lee. It works pretty well, no complains here.
import UIKit
import SwiftUI
extension UIViewController {
func addSubSwiftUIView<Content>(_ swiftUIView: Content, to view: UIView) where Content : View {
let hostingController = UIHostingController(rootView: swiftUIView)
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
view.bottomAnchor.constraint(equalTo: hostingController.view.bottomAnchor),
view.rightAnchor.constraint(equalTo: hostingController.view.rightAnchor)
]
NSLayoutConstraint.activate(constraints)
hostingController.didMove(toParent: self)
}
}
2. MSStickerView won’t auto-size
To create an MSStickerView inside SwiftUI I'm using the following code. The frame: passed to the StickerView is not applied though. Without .frame(minWidth: size, minHeight: size), nothing is shown because the size becomes virtually zero.
import Messages
import SwiftUI
import UIKit
struct StickerView: UIViewRepresentable {
var frame: CGRect
var sticker: MSSticker?
func makeUIView(context: Context) -> MSStickerView {
MSStickerView(frame: frame, sticker: sticker)
}
func updateUIView(_ uiView: MSStickerView, context: Context) {
}
}
@ViewBuilder
func makeStickerView(fromStickerData stickerData: StickerDataEntry, size: CGFloat = CGFloat(64)) -> some View {
if let sticker = try? MSSticker(contentsOfFileURL: stickerData.url!, localizedDescription: stickerData.description) {
StickerView(frame: CGRect(x: 0, y: 0, width: 408, height: 408), sticker: sticker)
.frame(minWidth: size, maxWidth: size, minHeight: size, maxHeight: size)
}
}
4. Delete Main.Storyboard
I’ve tried following similar instructions before and again just now, but to no avail. The result is a bank screen on the iPhone and the app icon in the middle of a blank screen on the simulator (running on a Mac mini M1). The relevant section of my Info.plist looks like this:
<key>NSExtension</key>
<dict>
<key>NSExtensionPrincipalClass</key>
<string>MessagesViewController</string>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.message-payload-provider</string>
</dict>
Topic:
App & System Services
SubTopic:
General
Tags: