Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI preview issue (have 'x86_64', need 'arm6) on Xcode 14
Hi, we recently starting moving toSwiftUI and unable to preview. we are getting a below crash. App is running using Rosetta on M1 Mac Xcode 14 iOS 16 All we did is to enable swift previews in build settings. Crash report for SwiftUI preview: PotentialCrashError: Update failed XCPreviewAgent may have crashed. Check ~/Library/Logs/DiagnosticReports for any crash logs from your application. ================================== |  RemoteHumanReadableError |   |  LoadingError: failed to load library at path "/Users/vamsianguluru/Library/Developer/Xcode/DerivedData/BapineMobile-fiuoxganfwfeexgxiewzascqsimr/Build/Intermediates.noindex/Previews/BapineApp/Products/Debug-iphonesimulator/BiometricLogin.framework/BiometricLogin": Optional(dlopen(/Users/vamsianguluru/Library/Developer/Xcode/DerivedData/BapineMobile-fiuoxganfwfeexgxiewzascqsimr/Build/Intermediates.noindex/Previews/BapineApp/Products/Debug-iphonesimulator/BiometricLogin.framework/BiometricLogin, 0x0000): tried: '/Users/vamsianguluru/Library/Developer/Xcode/DerivedData/BapineMobile-fiuoxganfwfeexgxiewzascqsimr/Build/Intermediates.noindex/Previews/BapineApp/Products/Debug-iphonesimulator/BiometricLogin.framework/BiometricLogin' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')), '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Users/vamsianguluru/Library/Developer/Xcode/DerivedData/BapineMobile-fiuoxganfwfeexgxiewzascqsimr/Build/Intermediates.noindex/Previews/BapineApp/Products/Debug-iphonesimulator/BiometricLogin.framework/BiometricLogin' (errno=2), '/Users/vamsianguluru/Library/Developer/Xcode/DerivedData/BapineMobile-fiuoxganfwfeexgxiewzascqsimr/Build/Intermediates.noindex/Previews/BapineApp/Products/Debug-iphonesimulator/BiometricLogin.framework/BiometricLogin' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')), '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/BiometricLogin.framework/BiometricLogin' (errno=2)) |   |  ================================== |   |  |  MessageSendFailure: Message send failure for <ServiceMessage 17: update>
5
1
3.0k
Nov ’23
Fixed SwiftUI window sizes in macOS with Xcode 14 and Ventura for macOS 11/12 targets
I have a project that requires a fixed window size. In previous versions of Xcode when I compile the project with the following : struct MyApp: App {     var body: some Scene {         WindowGroup {             ContentView()                 .frame(width: 800, height: 600)         }     } } It will result in a window with a fixed size of 800x600 (i.e. the window inherits the fixed content size) With Xcode 14 and macOS Ventura, this is no longer the case. The above code compiles but now the window is resizable, with the content inhabiting an 800x600 area. In Ventura there is the   .windowResizability(.contentSize) property but this is macOS 13 only. I need my app to be able to support macOS 11 and 12 and now the window behaviour is broken with the latest Xcode. Is there any way to get around this that doesn't involve running a seperate macOS 12/Xcode 13 environment?
3
4
5.7k
Jan ’24
SwiftUI List on maCOS: highlighting content in the selected row?
Hello all, In a SwiftUI List, when a row is selected, a blue selection is drawn in the selection, and foreground Text with the default primary color is automatically made white. For other views with custom colors, I'd like to be able to make sure they become tinted white to match the system apps. For example, see the blue dot on the selected row: Example code: List(selection: $selection) {     ForEach(0..<4) { index in         HStack {             Image(systemName: "circle.fill")                 .foregroundColor(.blue)             Text("Test")         }         .tag(index)     } } With NSTableCellView, there is the backgroundStyle property. I've searched all of the available environment variables, and couldn't find anything appropriate. I have also tried manually including an isSelected binding on a view for each row, but the selection binding is not updated by List until mouse-up, while the highlight is updated on mouse-down and drag, so this results in a flickery appearance and is not right either. Any tips on how to achieve the correct result here? Thanks! 🙏
4
2
3.2k
Dec ’23
ShareLink does not offer "save to files" when sharing "Transferable" items
In my app I try to use SwiftUI's ShareLink to offer sharing of the app's documents. I followed this video for defining the exported type and the document type. Unfortunately if I use any ShareLink initializer for sharing Transferable items, the option "save to files" is not offered on the displayed share sheet. (Only "copy" is offered, which works if pasted into the destination directory using the Files app, but that is not an acceptable workaround). PS: com.example.transferabletestis defined as conforming to com.apple.package import SwiftUI import UniformTypeIdentifiers extension UTType{     static let transferableTest = UTType(exportedAs: "com.example.transferabletest") } struct Document:Transferable{     static let filePackageURL = URL.documentsDirectory.appending(components: "0815.transferabletest")    public static var transferRepresentation: some TransferRepresentation {         FileRepresentation(exportedContentType: .transferableTest) { document in             _ = try? FileManager.default.createDirectory(at: Self.filePackageURL, withIntermediateDirectories: false)             FileManager.default.createFile(atPath: Self.filePackageURL.appending(components: "data").path(), contents: "Transferable Test\n".data(using: .utf8))             return SentTransferredFile(Document.filePackageURL)         }     } } struct ContentView: View {     var body: some View {         ShareLink("Share as tranferable item", item: Document(), preview: SharePreview("Test"))     } } Is this a bug? What am I doing wrong? Sharing the document using the ShareLink for URLs does offer "save to files" but I can't use that in my app for various reasons.
3
1
1.5k
Jun ’24
When set live activity dismissalPolicy: .after(endTime), the dynamic island not working
I have app that shows live activity and countdown till a date... VStack { Text("Countdown till You finish your homework")  Text(countdownTime, style: .timer) } After the time up, the live activity countup, the solution is to update the live activity via backgroundTask and this not always working, really apple sometimes fire the backgroundTask after hours. Another solution is to set dismissalPolicy: .after(countdownTime), but once I did that the dynamic island not working and the activity status is ended after right calling... await activity.end(using: state, dismissalPolicy: .after(countdownTime)) Can anyone help please, users feed back is why you we still see the old task on live activity. How come I can not update live activity? and how come if you set dismissalPolicy .after apple changes the activity status to ended and stop showing the dynamic island?
3
4
1.4k
Mar ’24
After iOS 16.1 Widgets + Extensions get the local form device language not from the app
Before iOS 16.1 my app was woking good, if the user set the app language to other language than his device language, my app, widget + extensions all use this language... After iOS 16.1 if user set the app language to other language than his device language, my app works with this language but the widget + extensions works with the device language, not my app language... For Example:     @Environment(\.locale.languageCode) private var userLocal before iOS 16.1 userLocal would be the app local, after iOS 16.1 it return the device local Any idea why Apple did that? is this a bug? How to set the widget language to match my app language now? even set .environment(\.locale, dose not work when use Strings(table: because it's still get the bundle that match device language.
3
2
1.4k
Apr ’24
iOS16 SwiftUI cannot figure out crash reason
I am getting random crash from time to time while using SwiftUI but i cannot find a way to get more context into the crash how to find the root cause? didn't even get more info while the crash happened while connected to XCode Version 14.1 (14B47b) OS Version: iPhone OS 16.1 (20B82) Release Type: User Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000019a9edeb4 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [45365] Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 SwiftUI 0x19a9edeb4 0x19a9c3000 + 175796 1 SwiftUI 0x19a9ede98 0x19a9c3000 + 175768 2 SwiftUI 0x19aa02da4 0x19a9c3000 + 261540 3 libswiftCore.dylib 0x1910dd138 Slice.index(after:) + 48 4 SwiftUI 0x19abd4d48 0x19a9c3000 + 2170184 5 SwiftUI 0x19ac16594 0x19a9c3000 + 2438548 6 libswiftCore.dylib 0x190f29678 BidirectionalCollection.index(_:offsetBy:) + 292 7 SwiftUI 0x19a9edd00 0x19a9c3000 + 175360 8 SwiftUI 0x19be30904 0x19a9c3000 + 21420292 9 SwiftUI 0x19bc2ffa8 0x19a9c3000 + 19320744 10 SwiftUI 0x19b7b1034 0x19a9c3000 + 14606388 11 SwiftUI 0x19b7afc20 0x19a9c3000 + 14601248 12 SwiftUI 0x19b7b21e4 0x19a9c3000 + 14610916 13 UIKitCore 0x1994e57d4 -[UICollectionView _selectItemAtIndexPath:animated:scrollPosition:notifyDelegate:deselectPrevious:performCustomSelectionAction:] + 1060 14 UIKitCore 0x1997314d4 -[UICollectionView touchesEnded:withEvent:] + 480 15 UIKitCore 0x1993e7514 forwardTouchMethod + 284 16 UIKitCore 0x1993e7514 forwardTouchMethod + 284 17 UIKitCore 0x1993e7514 forwardTouchMethod + 284 18 UIKitCore 0x1993e7514 forwardTouchMethod + 284 19 UIKitCore 0x1993185e0 _UIGestureEnvironmentUpdate + 5772 20 UIKitCore 0x199b9ce14 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 288 21 UIKitCore 0x1992dc31c -[UIGestureEnvironment _updateForEvent:window:] + 188 22 UIKitCore 0x1992e0c74 -[UIWindow sendEvent:] + 3268 23 UIKitCore 0x1992dff44 -[UIApplication sendEvent:] + 672 24 UIKitCore 0x1992df600 __dispatchPreprocessedEventFromEventQueue + 7084 25 UIKitCore 0x1993273e4 __processEventQueue + 5632 26 UIKitCore 0x199f790a4 updateCycleEntry + 168 27 UIKitCore 0x199837740 _UIUpdateSequenceRun + 84 28 UIKitCore 0x199e7efd0 schedulerStepScheduledMainSection + 172 29 UIKitCore 0x199e7e19c runloopSourceCallback + 92 30 CoreFoundation 0x1970fdf54 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 31 CoreFoundation 0x19710a32c __CFRunLoopDoSource0 + 176 32 CoreFoundation 0x19708e210 __CFRunLoopDoSources0 + 244 33 CoreFoundation 0x1970a3ba8 __CFRunLoopRun + 836 34 CoreFoundation 0x1970a8ed4 CFRunLoopRunSpecific + 612 35 GraphicsServices 0x1cfb05368 GSEventRunModal + 164 36 UIKitCore 0x1995873d0 -[UIApplication _run] + 888 37 UIKitCore 0x199587034 UIApplicationMain + 340 38 libswiftUIKit.dylib 0x19fb73308 UIApplicationMain(_:_:_:_:) + 104 39 Fyzio Klinik Doctor 0x10445b2d8 static UIApplicationDelegate.main() + 104 40 Fyzio Klinik Doctor 0x10445b260 static AppDelegate.$main() + 44 41 Fyzio Klinik Doctor 0x10445b450 main + 28 42 dyld 0x1b5700960 start + 2528 Thread 1: 0 libsystem_pthread.dylib 0x1e370eb90 start_wqthread + 0
1
1
730
Oct ’23
SwiftUI Widget not rendering Switch Toggle
I'm currently working on a swift widget for my flutter app. When I add a Toggle to my widget and run it, I don't see any toggle. struct MyWidgetEntryView : View {   @State private var on = true       var body: some View {     VStack(content: {       Text("I am title").font(.system(size: 20))       Text("I am text")       Toggle("I am toggle", isOn: $on)     })   } it does show if I change the toggleStyle to .button Toggle("I am toggle", isOn: $on).toggleStyle(.button) I'm using swift 5.5.2 and running it on an iPhone 12 simulator.
3
0
678
Sep ’23
SwiftUI NavigationLink freezing when tapped
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
12
2
6.4k
3w
SwiftUI MenuBarExtra not updating when State changes
hi is there any way to UPDATE dropdown content Text or do anything when "@State" changes ? cuz in normal SwiftUI views everything rerenders when "@State" changes expect this new "MenuBarExtra" code in "label:" part will update when "@State" change but where I added "ControlView()" it does not :/ example code: @State var secounds = 0     @State var timerRunning = false     let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()     var body: some Scene {         MenuBarExtra {             ControlView()         } label: {             Text("\(hours):\(minutes):\(secounds)")                 .onReceive(timer) { _ in                     }                 }         }         .menuBarExtraStyle(.window)     }          @ViewBuilder     func ControlView()->some View {         Grid(horizontalSpacing: 12, verticalSpacing: 12) {             GridRow {                 ZStack {                     RoundedRectangle(cornerRadius: 12, style: .continuous)                         .fill(.red)                         .frame(height: 75)                                          Text("\(timerRunning ? "Pause" : "Play")")                         .padding()                         .onTapGesture {                             timerRunning.toggle()                         }                 }             }         }         .padding(10)     }
3
3
1.2k
Oct ’23
Background image scales incorrectly when ignoring safe area
In a SwiftUI project I try to display a background image with ignoring safe area insets (to make it go edge to edge). However, the background scales incorrectly and doesn't respect its aspect ratio. Here is a small code example of the view structure that I'm using: struct ContentView: View {   var body: some View {     ZStack {       Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.").padding()     }.frame(maxHeight: .infinity).background(Image("dots").resizable().ignoresSafeArea().scaledToFill())   } } And an example image for testing (when using this image you can clearly see the circles become more like ovals in the SwiftUI app): Screenshot:
6
0
2k
6h
@Environment(\.dismiss) var dismiss - Infinite loop bug.
The following code works: struct SelectBatteryChemistryView: View {     @ObservedObject var model: SelectBatteryChemistryViewModel = .init()     @Environment(\.presentationMode) private var presentationMode     var body: some View {         VStack {             Spacer()             TitleText("BATTERY MODE")             SimpleModeSelectorView(                 selected: $model.batteryChemistry             )             .pickerStyle(.inline)             .frame(minHeight: 300)             PrimaryTitleButton(title: "SELECT") {                 if model.batteryChemistry == .user {                     model.customChemistryFlow = true                 } else {                     model.confirmBatterySettings()                 }             }             NavigationLink(                 destination: CustomBatteryChemistryView(),                 isActive: $model.customChemistryFlow             ) { EmptyView() }                 .isDetailLink(false)         }         .onReceive(model.$batterySettingsConfirmed) { batterySettingsConfirmed in             if batterySettingsConfirmed {                 //dismiss()             }         }         .onAppear() {             model.customChemistryFlow = false         }     } } The following code causes an infinite loop in the CustomBatteryChemistryView() initialiser. struct SelectBatteryChemistryView: View {     @ObservedObject var model: SelectBatteryChemistryViewModel = .init()     @Environment(\.dismiss) private var dismiss     var body: some View {         VStack {             Spacer()             TitleText("BATTERY MODE")             SimpleModeSelectorView(                 selected: $model.batteryChemistry             )             .pickerStyle(.inline)             .frame(minHeight: 300)             PrimaryTitleButton(title: "SELECT") {                 if model.batteryChemistry == .user {                     model.customChemistryFlow = true                 } else {                     model.confirmBatterySettings()                 }             }             NavigationLink(                 destination: CustomBatteryChemistryView(),                 isActive: $model.customChemistryFlow             ) { EmptyView() }                 .isDetailLink(false)         }         .onReceive(model.$batterySettingsConfirmed) { batterySettingsConfirmed in             if batterySettingsConfirmed {                 //dismiss()             }         }         .onAppear() {             model.customChemistryFlow = false         }     } } Adding the @Environment(.dismiss) object prevents the use of a navigation link. The program sits there with the stack infinitely calling the getter for the NavigationLink. It looks like an infinite loop on the accessor due to some strangeness related to the magic of the Dismiss environment object. How do we pass this on to the Dev team at Apple?
9
5
2.2k
Jan ’24
Print a SwiftUI view on macOS?
I made a test with a new XIB-based project using this code     func applicationDidFinishLaunching(_ aNotification: Notification) {         guard let content = window.contentView else {             print("Error: cannot access windows contentview!")             return         }                  let tv = NSTextView(frame: NSMakeRect(100, 300, 200, 40))         tv.string = "Text subview"         tv.font = NSFont.systemFont(ofSize: 30.0)         content.addSubview(tv)         let chartView = NSHostingView(rootView: myChart())         chartView.setFrameSize(content.frame.size)         content.addSubview(chartView)         content.printView(self)             } "myChart" is s sample view using Charts. The window does show the text and the chart but the print shows the text only. How can I get the SwiftUI-View printed? My goal is a PDF output of a SwiftUI view. There are already several older threads with similar questions but no solution, yet.
2
0
563
Mar ’24
NavigationStack inside NavigationSplitView on Mac
I've seen several posts regarding NavigationStack in a NavigationSplitView. All had specific issues and some were marked as resolved. I couldn't get any of the suggested solutions working on macOS so I'll present some stripped down examples, all part of FB11842563: 1. Sidebar Selection struct SidebarSelection: View {     @State var selection: Int?     @State var path: [Int] = []     var body: some View {         NavigationSplitView {             List(1...20, id: \.self, selection: $selection) { number in                     Text("I like \(number)")             }         } detail: {             NavigationStack(path: $path) {                 VStack {                     Image(systemName: "x.squareroot")                         .imageScale(.large)                         .foregroundColor(.accentColor)                     Text("This is the NavigationStack root")                 }                 .padding()                 .navigationDestination(for: Int.self) { number in                     Text("You chose \(number)")                 }             }         }         .onChange(of: selection) { newValue in             print("You clicked \(newValue)")             if let newValue {                 path.append(newValue)             }         }         .onChange(of: path) { newValue in             print("Path changed to \(path)")         }     } } If we run this and click: „I like 5“ „I like 6“ „I like 7“ We would expect the detail view to show: „You chose 5“ „You chose 6“ „You chose 7“ And the console to show: You clicked Optional(5) Path changed to [5] You clicked Optional(6) Path changed to [5, 6] You clicked Optional(7) Path changed to [5, 6, 7] What we actually see in the detail view is: „You chose 5“ „This is the NavigationStack root“ „You chose 7“ And the console shows: Update NavigationRequestObserver tried to update multiple times per frame. You clicked Optional(5) Path changed to [5] You clicked Optional(6) Path changed to [] You clicked Optional(7) Path changed to [7] 2. Sidebar and Stack Selection Now we copy the list to the navigationDestination: struct SidebarAndStackSelection: View {     @State var selection: Int?     @State var path: [Int] = []     var body: some View {         NavigationSplitView {             List(1...20, id: \.self, selection: $selection) { number in                     Text("I like \(number)")             }         } detail: {             NavigationStack(path: $path) {                 VStack {                     Image(systemName: "x.squareroot")                         .imageScale(.large)                         .foregroundColor(.accentColor)                     Text("This is the NavigationStack root")                 }                 .padding()                 .navigationDestination(for: Int.self) { number in                     VStack {                         Text("You chose \(number)")                         List(1...20, id: \.self, selection: $selection) { number in                             Text("I like \(number)")                         }                     }                 }             }         }         .onChange(of: selection) { newValue in             print("You clicked \(newValue)")             if let newValue {                 path.append(newValue)             }         }         .onChange(of: path) { newValue in             print("Path changed to \(path)")         }     } } We repeat our test from above, clicking either on the sidebar or in the detail view and we expect the same outcome. This time the detail view shows the expected screen and the path is not completely wiped out but it is also not appended: Update NavigationRequestObserver tried to update multiple times per frame. You clicked Optional(5) Path changed to [5] You clicked Optional(6) Path changed to [6] You clicked Optional(7) Path changed to [7] 3. Sidebar and Stack Selection, initialized Same as before, but now we initialize the view with a non-empty path: SidebarAndStackSelection(path: [1]) The app freezes on launch, CPU is at 100 percent and the console shows only: Update NavigationRequestObserver tried to update multiple times per frame. Update NavigationRequestObserver tried to update multiple times per frame. The SwiftUI instruments seem to show heavy activity of the Stack and the SplitView: 4. Selection only in Stack Once we remove the selection from the sidebar everything works as expected (adding the NavigationStack to the root view to be able to click on a number): struct SidebarWithoutSelectionButStack: View {          @State var selection: Int?     @State var path: [Int] = []          var body: some View {         NavigationSplitView {             List(1...20, id: \.self) { number in                     Text("I like \(number)")             }         } detail: {             NavigationStack(path: $path) {                 List(1...20, id: \.self, selection: $selection) { number in                     Text("I like \(number)")                 }                 .padding()                 .navigationDestination(for: Int.self) { number in                     VStack {                         Text("You chose \(number)")                         List(1...20, id: \.self, selection: $selection) { number in                             Text("I like \(number)")                         }                     }                 }             }         }         .onChange(of: selection) { newValue in             print("You clicked \(newValue)")             if let newValue {                 path.append(newValue)             }         }         .onChange(of: path) { newValue in             print("Path changed to \(path)")         }     } } Problem of course is, that now the sidebar is useless.
6
2
1.4k
Mar ’24
Problem with GeometryReader
Hello, I used GeometryReader to proportion the size of my Frames vertically regardless of the device. Yet the List on the Ipad contains 3 lines and only 1 on the Iphone. Where is my error in the code for this layout? Thanks in advance             GeometryReader { geo in                 VStack(spacing: 0){                     Text(getTimeString(m: self.minutes, s: self.seconds, c: self.centiseconds))                         .font(.system(size: min(geo.size.height, geo.size.width) * 0.05, design: .monospaced))                         .frame(height: UIScreen.main.bounds.height * 0.05)                         .onReceive(timer) {_ in                             if(self.running) {                                 self.timerCalcs()                             }                         }                                          Text("\(lapCount - 1)")                         .font(.system(size: min(geo.size.height, geo.size.width) * 0.25))                         .fontWeight(.bold)                         .frame(height: UIScreen.main.bounds.height * 0.25)                         .foregroundColor(.red)                                          ZStack {                         Text(self.lapTimes.last?.getLapSecondsString() ?? "")                             .font(.system(size: min(geo.size.height, geo.size.width) * 0.45))                             .fontWeight(.bold)                             .frame(height: UIScreen.main.bounds.height * 0.38)                         Rectangle().fill(Color.gray.opacity(0.1))                     }                                          HStack(spacing : 10){                             Button(action: {                                 if(!self.running) {                                     self.minutes = 0                                     self.seconds = 0                                     self.centiseconds = 0                                     self.lapTimes = []                                     self.lapMinutes = 0                                     self.lapSeconds = 0                                     self.lapCentiseconds = 0                                     self.lapCount = 1                                                                      } else {                                     self.lapTimes.append(LapTime(n: self.lapCount, m: self.lapMinutes, s: self.lapSeconds, c: self.lapCentiseconds))                                     self.lapCount += 1                                     self.lapMinutes = 0                                     self.lapSeconds = 0                                     self.lapCentiseconds = 0                                 }                             }) {                                 ZStack{                                     Circle().fill(Color.gray).frame(height: UIScreen.main.bounds.height * 0.12)                                     self.running ? Text("Lap").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced)) : Text("Reset").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced))                                 }                             }                             .padding(8)                             Spacer()                             Button(action: {                                 self.running = !self.running                             }) {                                 ZStack{                                     Circle().fill(self.running ? Color.red : Color.green).frame(height: UIScreen.main.bounds.height * 0.12).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced))                                     self.running ? Text("Stop").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced)) : Text("Start").foregroundColor(Color.white).font(.system(size: min(geo.size.height, geo.size.width) * 0.04, design: .monospaced))                                 }                             }                             .padding(8)                     }                                                                                        List{                         LapTime(n: self.lapCount, m: self.lapMinutes, s: self.lapSeconds, c: self.lapCentiseconds)                         ForEach(self.lapTimes.reversed()) { time in                             time                                                          }                        }                 }             }                      }
6
0
1.8k
Sep ’23
SwiftU keyboard toolbar disappearing after present additional .sheet
I added a keyboard toolbar inside ZStack. And it works right after appears as expected But after opening and closing another view over the .sheet modifier, The keyboard toolbar doesn't show anymore. ZStack { . .. TextField() .toolbar { ToolbarItemGroup(placement: .keyboard) { .... } } } .sheet(isPresent: $binding) { Some other view } Seems it happened after upgrading to iOS 16. Does anybody has the solution? Thanks
8
5
2.8k
May ’24
Localization settings hidden if only 1 preffered language in iOS
I have added additional localizations into my iOS app. iOS is not available in those languages. So I did as it is suggested that you redirect customers to app settings view UIApplication.openSettingsURLString and there they can select another app language. Unfortunately they do not see language selection if they do not have set at least 2 Preferred languages in General -> Languages & Region. Also it does not matter what languages they have there. If my app does not support those then it still shows all localizations available. Is there somehow to force it? So it would be visible always? Since most people in my country have iPhones only in English but would like to use Apps in their native language.. Since they do not have 2 preferred languages they cant see the selection :(
6
6
2.8k
Mar ’24
Swift UI Preview for Multiple Entity
Hello, I've created multiple Entity in CoreData, that has a relationship to one another. However, I'm unable to create @discardableResult to use in SwiftUI preview. /// Entity data for use with canvas previews. static var preview: Entity1 {         let entities1 = Entity1.makePreviews(count: 1)         return entities1[0] } @discardableResult static func makePreviews(count: Int) -&gt; [Entity1] {         var contents = [Entity1]()         let viewContext = PersistenceController.preview.container.viewContext         let persistenceController = PersistenceController.shared         for index in 0..&lt;count {             let entities1 = Entity1(context: viewContext)             entities1.id = UUID()             entities1.title = "Amazing day!"             let photo = Photo(context: viewContext)             let imageData = UIImage(named: "Golden Temple")?.jpegData(compressionQuality: 1) ?? Data()             photo.linkedToJournal = journal             let thumbnail = Thumbnail(context: viewContext)             let thumbnailData = persistenceController.thumbnail(with: imageData)?.jpegData(compressionQuality: 1)             thumbnail.data = thumbnailData             thumbnail.photo = photo             let photoDataObject = PhotoData(context: viewContext)             photoDataObject.data = imageData             photoDataObject.photo = photo             contents.append(entities1)         }         return contents } You may also try to use the sample code from https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users to build a SwiftUI Preview. Appreciate if you could suggest how to build a SwiftUI preview as it saves a lot of development effort and time. Thank you very much!
1
0
1k
Nov ’23