I want to share UserDefaults between main App and macOS Widget, in iOS I can do it using AppGroups, but how to do it between macOS Widget and main App, because macOS widget's AppGroup require to use "Team Identifier" as prefix and main App's AppGroup require prefix to be "group" so how can I share UserDefaults between the two?
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Post
Replies
Boosts
Views
Activity
I have an app with a TabView containing a view representable containing a SwiftUI View with a toolbar. The representable is providing the toolbar while the .toolbar modifier provides the content.
Everything works normally on iOS 17, but on iOS 18 the toolbar contents are not showing.
Is this a iOS 18 bug?
See the code below for a simplified example.
import SwiftUI
@main
struct TestApp: App {
@State var selection: String = "one"
var body: some Scene {
WindowGroup {
TabView(selection: $selection) {
Representable()
.tabItem {
Text("One")
}
.tag("one")
}
}
}
}
struct Representable: UIViewControllerRepresentable {
let navigationController = UINavigationController()
func makeUIViewController(context: Context) -> UINavigationController {
navigationController.pushViewController(UIHostingController(rootView: ToolbarView()), animated: false)
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {}
}
struct ToolbarView: View {
var body: some View {
NavigationLink("Navigate") {
ToolbarView()
}
.toolbar {
ToolbarItem(placement: .principal) {
Text("Top")
}
}
}
}
Hello, since the last version of iOS and WatchOS I have a problem with this code.
This is the minimal version of the code, it have two pickers inside a view of a WatchOS App.
The problem its with the focus, I can't change the focus from the first picker to the second one.
As I said before, it was working perfectly in WatchOS 10.0 but in 11 the problems started.
struct ParentView: View {
@FocusState private var focusedField: String?
var body: some View {
VStack {
ChildView1(focusedField: $focusedField)
ChildView2(focusedField: $focusedField)
}
}
}
struct ChildView1: View {
@FocusState.Binding var focusedField: String?
@State private var selectedValue: Int = 0
var body: some View {
Picker("First Picker", selection: $selectedValue) {
ForEach(0..<5) { index in
Text("Option \(index)").tag("child\(index)")
}
}.pickerStyle(WheelPickerStyle()).focused($focusedField, equals: "first")
}
}
struct ChildView2: View {
@FocusState.Binding var focusedField: String?
@State private var selectedValue: Int = 0
var body: some View {
Picker("Second Picker", selection: $selectedValue) {
ForEach(0..<5) { index in
Text("Option \(index)").tag("childTwo\(index)")
}
}.pickerStyle(WheelPickerStyle()).focused($focusedField, equals: "second")
}
}
When you do vertical scrolling on the second picker, the focus should be on it, but it dosnt anything.
I try even do manually, setting the focusState to the second one, but it sets itself to nil.
I hope that you can help me, thanks!
I am using a Mac Catalyst with SwiftUI for our document-based app with DocumentGroup. The issue is that when we create a new document or open an existing one, the opened view is completely blank. It is only blank/empty when the "Optimzie for Mac" is checked. If it is "Scaled t oMatch iPad", then it works well.
Xcode 16.1
macOS 15.1
struct DocumentGroupTestApp: App {
var body: some Scene {
DocumentGroup(newDocument: WritingAppDocument()) { file in
TestView() // it is empty when it gets opened. It does not work if the option "Optimize for Mac" is checked. If it is scale iPad, then it works.
}
}
}
struct TestView: View {
var body: some View {
Text("Hello, World!")
}
}
In iOS18 the user can change their Home Screen customization to choose either light, dark, or tinted. If they choose tinted the widgets are rendered using the "accented" rendering mode and without a background.
Is there some way to override so that the tinted mode is ignore completely and the widgets render as full color?
I know about WidgetAccentedRenderingMode (https://developer.apple.com/documentation/widgetkit/widgetaccentedrenderingmode) but that's only for images, not the whole control and doesn't help with the background also being removed in the tinted mode.
I have this code to make ARVR Stereo View To Be Used in VR Box Or Google Cardboard, it uses iOS 18 New RealityView but it is not Act as an AR but rather Static VR on a Camera background so as I move the iPhone the cube move with it and that's not suppose to happen if its Anchored in a plane or to world coordinate.
import SwiftUI
import RealityKit
struct ContentView : View {
let anchor1 = AnchorEntity(.camera)
let anchor2 = AnchorEntity(.camera)
var body: some View {
HStack (spacing: 0){
MainView(anchor: anchor1)
MainView(anchor: anchor2)
}
.background(.black)
}
}
struct MainView : View {
@State var anchor = AnchorEntity()
var body: some View {
RealityView { content in
content.camera = .spatialTracking
let item = ModelEntity(mesh: .generateBox(size: 0.25), materials: [SimpleMaterial()])
anchor.addChild(item)
content.add(anchor)
anchor.position.z = -1.0
anchor.orientation = .init(angle: .pi/4, axis:[0,1,1])
}
}
}
the thing is if I remove .camera like this
let anchor1 = AnchorEntity()
let anchor2 = AnchorEntity()
It would work as AR Anchored to world coordinates but on the other hand is does not work but on the left view only not both views
Meanwhile this was so easy before RealityView and SwiftUI by cloning the view like in ARSCNView Example :
import UIKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
//create Any Two ARSCNView's in Story board
// and link each to the next (dont mind dimensions)
@IBOutlet var sceneView: ARSCNView!
@IBOutlet var sceneView2: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
sceneView.delegate = self
sceneView.session.delegate = self
// Create SceneKit box
let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.01)
let item = SCNNode(geometry: box)
item.geometry?.materials.first?.diffuse.contents = UIColor.green
item.position = SCNVector3(0.0, 0.0, -1.0)
item.orientation = SCNVector4(0, 1, 1, .pi/4.0)
// retrieve the ship node
sceneView.scene.rootNode.addChildNode(item)
}
override func viewDidLayoutSubviews() // To Do Add the 4 Buttons
{
// Stop Screen Dimming or Closing While The App Is Running
UIApplication.shared.isIdleTimerDisabled = true
let screen: CGRect = UIScreen.main.bounds
let topPadding: CGFloat = self.view.safeAreaInsets.top
let bottomPadding: CGFloat = self.view.safeAreaInsets.bottom
let leftPadding: CGFloat = self.view.safeAreaInsets.left
let rightPadding: CGFloat = self.view.safeAreaInsets.right
let safeArea: CGRect = CGRect(x: leftPadding, y: topPadding, width: screen.size.width - leftPadding - rightPadding, height: screen.size.height - topPadding - bottomPadding)
DispatchQueue.main.async
{
if self.sceneView != nil
{
self.sceneView.frame = CGRect(x: safeArea.size.width * 0 + safeArea.origin.x, y: safeArea.size.height * 0 + safeArea.origin.y, width: safeArea.size.width * 0.5, height: safeArea.size.height * 1)
}
if self.sceneView2 != nil
{
self.sceneView2.frame = CGRect(x: safeArea.size.width * 0.5 + safeArea.origin.x, y: safeArea.size.height * 0 + safeArea.origin.y, width: safeArea.size.width * 0.5, height: safeArea.size.height * 1)
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let configuration = ARWorldTrackingConfiguration()
sceneView.session.run(configuration)
sceneView2.scene = sceneView.scene
sceneView2.session = sceneView.session
}
}
And here is the video for it
I have a Map within a SwiftUI app that has the selection parameter set to an optional MapSelection.
I need to be able to select MapFeatures which works as expected as well as MKMapItems which are added to the map. The MKMapItems are not selectable.
Is it possible to make it such that the Map allows the user to select MKMapItems as well as MapFeatures?
Is it possible to get a MapFeature from an MKMapItem?
Hello,
I'm seeing a strange error on another user's device where the SwiftUI file importer doesn't do anything at all. When selecting multiple files and hitting "open", the importer just freezes. Here's a video showing the problem: https://streamable.com/u5grgy
I'm unable to replicate on my own device, so I'm not sure what could be going on. I have startAccessingSecurityScopedResource and stopAccessingSecurityResource everywhere I access a file from fileImporter as well.
I have a Split View with the sidebar, content, and detail. Everything is working, but when I select on a NavigationLink in my detail view, the back button is seen next to the title above the content view. I want that back button to be displayed in the top bar on the left side of the detail view. I was expecting it to do this automatically, but I must be missing something.
This is where I want it to appear.
This is where it appears.
I made a simplified version of my code, because it would be too much to post but this has the same behavior.
struct TestView: View {
enum SidebarSelections {
case cycles
}
@State private var sidebarSelection: SidebarSelections = .cycles
var body: some View {
NavigationSplitView(sidebar: {
List(selection: $sidebarSelection, content: {
Label("Cycles", systemImage: "calendar")
.tag(SidebarSelections.cycles)
})
}, content: {
switch sidebarSelection {
case .cycles:
NavigationStack {
List {
// Displayed in Content
NavigationLink("Cycle link", destination: {
// Displayed in the Detail
NavigationStack {
List {
NavigationLink("Detail Link", destination: {
Text("More details")
})
}
}
})
}
}
}
}, detail: {
ContentUnavailableView("Nothing to see here", systemImage: "cloud")
})
}
}
Is what I want to do possible? Here is a Stack Overflow post that had it working at one point.
I have an issue using RealityView to show two screens of AR, while I did succeed to make it as a non AR but now my code not working.
Also it is working using Storyboard and Swift with SceneKit, so why it is not working in RealityView?
import SwiftUI
import RealityKit
struct ContentView : View {
var body: some View {
HStack (spacing: 0){
MainView()
MainView()
}
.background(.black)
}
}
struct MainView : View {
@State var anchor = AnchorEntity()
var body: some View {
RealityView { content in
let item = ModelEntity(mesh: .generateBox(size: 0.2), materials: [SimpleMaterial()])
content.camera = .spatialTracking
anchor.addChild(item)
anchor.position = [0.0, 0.0, -1.0]
anchor.orientation = .init(angle: .pi/4, axis:[0,1,1])
// Add the horizontal plane anchor to the scene
content.add(anchor)
}
}
}
I am creating a UIKit application but that contains SwiftUI Views embedded using the hostingcontroller.
I have a particular approach for it..but it requires instantiating a swiftUI view, creating a hostingcontroller object from it and storing a reference to it. So that later If I wanted to update the view, I can simply get the reference back and update the swiftUI view using it.
I wanted to understand what does apple recommends on this. Can we store a swiftUI instance? Does it cause any issue or it is okay to do so?
I was hoping for an update of SwiftData which adopted the use of shared and public CloudKit containers, in the same way it does for the private CloudKit container.
So firstly, a big request to any Apple devs reading, for this to be a thing!
Secondly, what would be a sensible way of adding a shared container in CloudKit to an existing app that is already using SwiftData?
Would it be possible to use the new DataStore method to manage CloudKit syncing with a public or shared container?
You'll have to forgive me, I am still pretty new to Swift, but I'm really struggling to figure out what I'm doing wrong or how I can fix it. I'm working on an app that generates an image from some views and then exports that image, but it always returns this very vague error:
The operation couldn’t be completed. (SwiftUI.FileExportOperation.Error error 0.)
Here's most of the program:
import SwiftUI
import UniformTypeIdentifiers
struct ContentView: View {
@State private var backgroundColor = Color.black
@State private var fileExporterIsPresented = false
@State private var image: NSImage?
@State private var fileExporterErrorAlertIsPresented = false
@State private var fileExporterErrorDescription: String?
var body: some View {
let wallpaper = Rectangle()
.foregroundStyle(backgroundColor)
.aspectRatio(16 / 9, contentMode: .fit)
VStack {
wallpaper
.clipShape(.rect(cornerRadius: 10))
.overlay {
RoundedRectangle(cornerRadius: 10)
.strokeBorder(.separator, lineWidth: 5)
}
ColorPicker("Background Color", selection: $backgroundColor, supportsOpacity: false)
Button("Generate Wallpaper") {
let renderer = ImageRenderer(content: wallpaper.frame(width: 3840, height: 2160))
image = renderer.nsImage
fileExporterIsPresented = true
}
.fileExporter(
isPresented: $fileExporterIsPresented,
item: image,
contentTypes: [UTType.heic, UTType.png]
) { result in
if case .failure(let error) = result {
fileExporterErrorDescription = error.localizedDescription
fileExporterErrorAlertIsPresented = true
}
}
.alert("File Exporter Failure", isPresented: $fileExporterErrorAlertIsPresented, actions: {
Button("OK") {}
}, message: {
if let fileExporterErrorDescription {
Text(fileExporterErrorDescription)
}
})
.dialogSeverity(.critical)
}
.padding()
}
}
#Preview {
ContentView()
}
Working on a macOS app. I need to display user-added images as a background to the view, with all of:
Tiling (auto repeat in both axes)
Scaling (user-configured scale of the image)
Offset (user-configured offset)
I've been able to achieve scaling and offset with:
Image(nsImage: nsImage)
.scaleEffect(mapImage.scale)
.offset(mapImage.offset)
.frame(width: scaledImageSize.width, height: scaledImageSize.height)
But when I try to incorporate tiling into that with .resizable(resizingMode: .tile) everything breaks.
Is there a way to position the "anchor" of an image, scale it, and tile it in both axes to fill a container view?
Hello team,
We recently found a EXC_BAD_ACCESS crash when using UIHostingControllers on a SPM local Package in our application. This is happening from time to time when we run the app on simulators using Debug configurations.
Also, this issue is consistent when we run application tests, there is something weird that we found after making a research... If we disable app test target and only keep packages tests, the crash is not happening, but as soon as we re-enable the app test target from the test suite the crash returns.
This is the full error message:
Thread 1: EXC_BAD_ACCESS (code=1, address=0xbad4017) A bad access to memory terminated the process.
Is this s known issue? We've been performing explorations for some days and couldn't find any real solution for this.
A basic call on UIHostingController inside of a SPM local Package is enough to make the app crash, nothing custom being done:
UIHostingController(rootView: MyView())
I have this code to make ARVR Stereo View To Be Used in VR Box Or Google Cardboard, it uses iOS 18 New RealityView but for some reason the left side showing the Entity (Box) more near to the camera than the right side which make it not identical, I wonder is this a bug and need to be fixed or what ? thanx
Here is the code
import SwiftUI
import RealityKit
struct ContentView : View {
let anchor1 = AnchorEntity(.camera)
let anchor2 = AnchorEntity(.camera)
var body: some View {
HStack (spacing: 0){
MainView(anchor: anchor1)
MainView(anchor: anchor2)
}
.background(.black)
}
}
struct MainView : View {
@State var anchor = AnchorEntity()
var body: some View {
RealityView { content in
content.camera = .spatialTracking
let item = ModelEntity(mesh: .generateBox(size: 0.25), materials: [SimpleMaterial()])
anchor.addChild(item)
content.add(anchor)
anchor.position.z = -1.0
anchor.orientation = .init(angle: .pi/4, axis:[0,1,1])
}
}
}
And Here is the View
Hello, I've created an app that follows the user as they navigate through public transport.
I want the camera to follow the user and at the same time I want the camera distance (elevation) to change dynamically depending on speed and other factors.
I've tried a first approach using camera keyframes, but I've noticed a lot of crashes when the app comes back to the foreground.
.mapCameraKeyframeAnimator(trigger: cameraFrame) { camera in
KeyframeTrack(\MapCamera.centerCoordinate) {
LinearKeyframe(cameraFrame.center, duration: cameraFrame.duration, timingCurve: cameraFrame.curve)
}
KeyframeTrack(\MapCamera.distance) {
LinearKeyframe(cameraFrame.distance, duration: cameraFrame.duration, timingCurve: cameraFrame.curve)
}
}
Some logs mention wrong center coordinates (nan, nan) but when I print them, it's show me valid coordinates.
I've also tried manually setting the camera for each position update, but the result is not smooth.
position = .camera(
.init(.init(
lookingAtCenter: newPosition,
fromDistance: cameraElevation,
pitch: .zero,
heading: .zero)
)
)
What's the best way to achieve this?
Hi, I have the view below that I want it to get any sort of SwiftData model and display and string property of that module, but I get the error mentioned below as well, also the preview have an error as below, how to fix it ? I know its little complicated.
Error for the view GWidget
" 'init(wrappedValue:)' is unavailable: The wrapped value must be an object that conforms to Observable "
Error of preview
" Cannot use explicit 'return' statement in the body of result builder 'ViewBuilder' "
3, Code
#Preview {
do {
let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: Patient.self, configurations: configuration)
let example = Patient(firstName: "Ammar S. Mitoori", mobileNumber: "+974 5515 7818", homePhone: "+974 5515 7818", email: "ammar.s.mitoori@gmail.com", bloodType: "O+")
// Pass the model (Patient) and the keyPath to the bloodType property
return GWidget(model: example, keyPath: \Patient.bloodType)
.modelContainer(container)
} catch {
fatalError("Fatal Error")
}
}
4. Code for the Gwidget View
```import SwiftUI
import SwiftData
struct GWidget<T>: View {
@Bindable var model: T
var keyPath: KeyPath<T, String> // Key path to any string property
// Variables for the modified string and the last character
var bloodTypeWithoutLast: String {
let bloodType = model[keyPath: keyPath]
return String(bloodType.dropLast())
}
var lastCharacter: String {
let bloodType = model[keyPath: keyPath]
return String(bloodType.suffix(1))
}
var body: some View {
VStack(alignment: .leading) {
Text("Blood Type")
.font(.footnote)
.foregroundStyle(sysPrimery07)
HStack (alignment: .lastTextBaseline) {
Text(bloodTypeWithoutLast)
.fontWeight(.bold)
.font(.title2)
.foregroundStyle(sysPrimery07)
VStack(alignment: .leading, spacing: -5) {
Text(lastCharacter)
.fontWeight(.bold)
Text(lastCharacter == "+" ? "Positive" : "Negative")
}
.font(.caption2)
.foregroundStyle(lastCharacter == "+" ? .green : .pink)
}
}
}
}
Hi
When connecting a SwiftData module property to a SwiftUI view such as a text field and the field changes by user the property get updated in the SwiftData database, now suppose I want to run a validation code or delay updates to Database till use click a submit button how to do that ? delay those auto updates if we can name it ?
Kind Regards
Code Example
import SwiftUI
import SwiftData
struct GListSel2: View {
@Bindable var patient: Patient
var body: some View {
HStack {
TextField("Gender", text: $patient.gender)
}
}
}