Files
__mahjong/components/render/ios/RenderIOS.swift
T
2026-10-22 15:55:54 +03:00

75 lines
3.1 KiB
Swift

import SwiftUI
import UIKit
// The prebuilt raylib iOS framework owns the app entry point (main()/
// AppDelegate/SceneDelegate in rcore_ios.c). Its SceneDelegate creates the
// window, installs GameViewController as the root and only then calls
// ios_ready(), so by the time rcios_present_overlay() runs there is already a
// key window with a GL-backed root view.
//
// We deliberately do NOT create a second UIWindow: that would sit at a fixed
// windowLevel and break alerts/buttons later. Instead we add the SwiftUI
// content as a child UIViewController of raylib's root view controller, so:
// - buttons receive touches through the normal responder chain;
// - .alert / sheets present correctly in the same window;
// - rotation and geometry changes apply to both layers at once.
//
// ChkgfxComponent/ChkgfxVM live here because the component lifecycle is
// otherwise driven by the (iOS-unavailable) SwiftUI app shell.
enum RenderIOS {
static let chkgfx = ChkgfxComponent()
static let chkgfxVM = ChkgfxVM()
// Inert on iOS (the raylib framework drives the scene), but the generated
// dialect refers to them, so keep them alive.
static let render = RenderComponent()
static let renderVM = RenderVM()
}
@_cdecl("rcios_present_overlay")
public func rciosPresentOverlay() {
otherSetupConsoleLogging(RenderIOS.chkgfx.ctrl, "Chkgfx")
RenderIOS.chkgfx.setup()
DispatchQueue.main.async {
guard let scene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first(where: { $0.activationState == .foregroundActive })
?? UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene }).first
else { return }
// raylib's SceneDelegate made its window key before calling ios_ready().
guard let window = scene.windows.first(where: { $0.isKeyWindow })
?? scene.windows.first,
let host = window.rootViewController
else { return }
let root = ChkgfxView(RenderIOS.chkgfxVM)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
let hosting = UIHostingController(rootView: root)
hosting.view.backgroundColor = .clear
// The UI is a passive title for now. Once it gains buttons, drop this
// line; touches will then stay in the SwiftUI layer over the whole
// screen instead of reaching raylib's GameViewController.
hosting.view.isUserInteractionEnabled = false
host.addChild(hosting)
hosting.view.frame = host.view.bounds
hosting.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
host.view.addSubview(hosting.view)
hosting.didMove(toParent: host)
// addChild retains the hosting controller for as long as it stays
// attached, so no extra strong reference is needed here.
OverlayHost.retained = hosting
}
}
// Optional handle for later use (e.g. presenting an alert from the hosting
// controller). The parent view controller keeps it alive while attached.
private enum OverlayHost {
static weak var retained: UIViewController?
}