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

Problem with NavigationLink
I am making application where I use navigation link to navigate from bottom menu to other views, and there is a problem when I change view a few times because views start stacking and when I set navigationBarBackButtonHidden(false) I can see on left side a lot of back button. This generate big problem because after changing views I got warning Abnormal number of gesture recognizer dependencies: 100. System performance may be affected. Please investigate reducing gesture recognizers and/or their dependencies. And after some more changes everything from screen is pushed down back button. Is there any solution to close previous view from we came? There is code: // // BottomMenu.swift // SpaceManager // // Created by Kuba Kromomołowski on 04/05/2024. // import SwiftUI import Firebase import FirebaseAuth struct BottomMenu: View { @StateObject var logManager = MainViewModel() @StateObject var mvm = MenuViewModel() @State var condition1: Bool = true @State var condition2: Bool = false @State var condition3: Bool = false // @StateObject private var cameraViewModel = CameraViewModel() var body: some View { HStack{ Group{ //.navigationBarBackButtonHidden(true) Spacer() BtnMenu(btnText: "Dodaj", btnIcon: "plus.app.fill", destinationView:AnyView(LoggedMainView()), isActive: condition1 ) Spacer() BtnMenu(btnText: "Szukaj", btnIcon: "magnifyingglass", destinationView:AnyView(SearchView()), isActive: condition2 ) Spacer() BtnMenu(btnText: "Profil", btnIcon: "person.crop.circle.fill", destinationView:AnyView(ProfileView()), isActive: condition3 ) Spacer() }.padding(.bottom, 30) .font(.system(size: 20)) } } } #Preview { BottomMenu() } // // BtnMenu.swift // SpaceManager // // Created by Kuba Kromomołowski on 04/05/2024. // import SwiftUI struct BtnMenu: View { var btnText: String var btnIcon: String var destinationView: AnyView @State var isActive: Bool = true var body: some View { NavigationLink{ destinationView } label: { ZStack { Text("\(Image(systemName: btnIcon)) \(btnText)") } }.disabled(isActive) } }
0
0
13
32m
Use of SceneDelegate not working
I am trying to configure scenes to capture a redirect URL after a successful login attempt. I am using OAuth code flow. This is the code I have so far: ios_app.swift import SwiftUI @main struct ios_appApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate let persistenceController = PersistenceController.shared @StateObject private var authState = AuthState() var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) .environmentObject(authState) } } } AppDelegate.swift import UIKit import AWSMobileClient import GoogleSignIn class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { print("AppDelegate: didFinishLaunchingWithOptions") AWSMobileClient.default().initialize { (userState, error) in if let userState = userState { print("UserState: \(userState)") } else if let error = error { print("Error initializing AWSMobileClient: \(error.localizedDescription)") } } GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in if let error = error { print("Error restoring previous Google Sign-In: \(error.localizedDescription)") } } return true } } SceneDelegate.swift import UIKit import SwiftUI import GoogleSignIn class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { print("SceneDelegate: scene willConnectTo") guard let windowScene = (scene as? UIWindowScene) else { print("SceneDelegate: Invalid windowScene") return } let window = UIWindow(windowScene: windowScene) let contentView = ContentView().environmentObject(AuthState()) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() print("SceneDelegate: window initialized and visible") } func sceneDidDisconnect(_ scene: UIScene) { print("SceneDelegate: sceneDidDisconnect") } func sceneDidBecomeActive(_ scene: UIScene) { print("SceneDelegate: sceneDidBecomeActive") } func sceneWillResignActive(_ scene: UIScene) { print("SceneDelegate: sceneWillResignActive") } func sceneWillEnterForeground(_ scene: UIScene) { print("SceneDelegate: sceneWillEnterForeground") } func sceneDidEnterBackground(_ scene: UIScene) { print("SceneDelegate: sceneDidEnterBackground") } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url else { print("SceneDelegate: No URL found in URLContexts") return } print("SceneDelegate: openURLContexts with URL: \(url)") if GIDSignIn.sharedInstance.handle(url) { print("SceneDelegate: Google Sign-In handled URL") return } if url.scheme == "myurlscheme" || (url.scheme == "https" && url.host == "mydomain.com" && url.path == "/mobile-auth-callback") { print("SceneDelegate: Handling auth response for URL: \(url)") AuthService.shared.handleOAuthCallback(url: url) } else { print("SceneDelegate: URL scheme not handled: \(url.scheme ?? "No scheme")") } } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { print("SceneDelegate: continue userActivity") if userActivity.activityType == NSUserActivityTypeBrowsingWeb { if let url = userActivity.webpageURL { handleUniversalLink(url: url) } } } private func handleUniversalLink(url: URL) { print("SceneDelegate: Handling universal link: \(url)") if url.path.contains("/mobile-auth-callback") { let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems let code = queryItems?.first(where: { $0.name == "code" })?.value if let code = code { print("SceneDelegate: Received code: \(code)") AuthService.shared.exchangeCodeForToken(code: code) } else { print("SceneDelegate: No code found, handling email/password callback") AuthService.shared.handleEmailPasswordCallback(url: url) } } } } Also introduced this configuration in Info.plist: <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> <true/> <key>UISceneConfigurations</key> <dict> <key>UIWindowSceneSessionRoleApplication</key> <array> <dict> <key>UISceneConfigurationName</key> <string>Default Configuration</string> <key>UISceneDelegateClassName</key> <string>ios-app.SceneDelegate</string> </dict> </array> </dict> </dict> ...Other parameters </dict> </plist> I am using the simulator to launch my app and can see AppDelegate related logs but I am not seeing any SceneDelegate logs (I suppose because it is not being initialized nor called). I have tried restarting the computer/Xcode, clean and rebuild the application but none of the things I tested work. Is there any part of my code wrong? Any other idea here?
0
0
25
2h
Issues Supporting All Accessibility Features with a Custom Font
I am in the process of adding my company's brand font to our SwiftUI app. I am able to implement the font using the provided public APIs so that text styles / dynamic type and the font weight modifier in SwiftUI work correctly. However we are unable to implement custom font in such a way that text styles / dynamic type, the font weight modifier, and the bold text accessibility setting all work at the same time. Am I missing an implementation detail so that all these features work correctly? Font Setup The font files were modified to better support SwiftUI: The font style name metadata was modified to match the name the .fontWeight(...) modifier expects. This was done with Typelight. The font weight value (100/200/300) was modified so that the underlying weight value matches the value the .fontWeight(...) modifier expects. See "Using custom fonts with SwiftUI" by Matthew Flint. The font files were imported via the Info.plist. Examples Font Weight Comparison San Fransisco: Text("#100") .font(.largeTitle) .fontWeight(.ultraLight) Overpass by Name: Text("#100") .font(.custom("Overpass-UltraLight", size: 34, relativeTo: .largeTitle)) Overpass by Weight: Text("#100") .fontWeight(.ultraLight) .font(.custom("Overpass", size: 34, relativeTo: .largeTitle)) Legibility Weight Test When using the .fontWeight(...) modifier, the custom font does not change weights when the bold text accessibility setting is enabled. Dynamic type size works as expected. Normal legibility weight: Bold legibility weight: Dynamic Type Size: Use UIFont Using UIFont to load the custom font files and initializing a Font with the UIFont breaks dynamic type: Bold type also does not work: Custom Modifier Creating a custom modifier allows us to support dynamic type and manually handle bold text. However it creates a conflicting API to SwiftUI's .fontWeight(...) modifier. struct FontModifier: ViewModifier { enum UseCase { case paragraph case headline } enum Weight { case light case regular case heavy } @Environment(\.legibilityWeight) var legibilityWeight var useCase: UseCase var weight: Weight init(_ useCase: UseCase, _ weight: Weight) { self.useCase = useCase self.weight = weight } var resolvedHeadlineWeight: String { let resolvedLegibilityWeight = legibilityWeight ?? .regular switch weight { case .light: switch resolvedLegibilityWeight { case .regular: return "Light" case .bold: return "Semibold" @unknown default: return "Light" } case .regular: switch resolvedLegibilityWeight { case .regular: return "Regular" case .bold: return "Bold" @unknown default: return "Regular" } case .heavy: switch resolvedLegibilityWeight { case .regular: return "Heavy" case .bold: return "Black" @unknown default: return "Heavy" } } } var resolvedParagraphWeight: Font.Weight { switch weight { case .light: return .light case .regular: return .regular case .heavy: return .heavy } } var resolvedFont: Font { switch useCase { case .paragraph: return .system(.largeTitle).weight(resolvedParagraphWeight) case .headline: return .custom("Overpass-\(resolvedHeadlineWeight)", size: 34, relativeTo: .largeTitle) } } func body(content: Content) -> some View { content .font(resolvedFont) } } GridRow { Text("Aa") .modifier(FontModifier(.paragraph, .regular)) Text("Aa") .modifier(FontModifier(.paragraph, .heavy)) Text("Aa") .modifier(FontModifier(.headline, .regular)) Text("Aa") .modifier(FontModifier(.headline, .heavy)) } Font Environment Value The font environment value does not contain font weight information when the fontWeight(...) modifier is used.: struct DumpFontTest: View { @Environment(\.font) var font var body: some View { Text("San Fransisco") .onAppear { print("------------") dump(font) } } }
0
1
34
3h
Really High Energy Use
I'm developing an app where users can select items to add to a screen, similar to creating a Canva presentation or choosing blocks in Minecraft. However, I'm encountering an issue with energy usage. When users click the arrows to browse different items, the energy use spikes significantly. Although it returns to normal after a while, continuous clicking causes the energy use to skyrocket. The images I'm using are 500x500 pixels. Ideally, I would like to avoid caching all the images, as the app might have up to 500 items and caching them all would consume too much memory. I have tried numerous way to avoid this but I just can’t seem to make it work. Would anyone know how to avoid such problem? I have included a picture of the energy use when just opened, and one after like 10 seconds of continuously clicking on an arrow to see more items. Also a picture of how the app looks. struct ContentView: View { struct babyBackground { var littleImage = "" } @State var firstSet: [babyBackground] = [ babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape"), babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape") ] @State var secondSet: [babyBackground] = [ babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape"), babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), babyBackground(littleImage: "anotherShape"), babyBackground(littleImage: "circle") ] @State var thirdSet: [babyBackground] = [ babyBackground(littleImage: "circle"), babyBackground(littleImage: "square"), babyBackground(littleImage: "triangle"), ] let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 4) func createBackgroundGridView(for backgrounds: [babyBackground], columns: [GridItem] ) -> some View { LazyVGrid(columns: columns, spacing: 10) { ForEach(0..<backgrounds.count, id: \.self) { index in Button(action: { }, label: { if let path = Bundle.main.path(forResource: backgrounds[index].littleImage, ofType: "png"), let uiImage = UIImage(contentsOfFile: path) { Image(uiImage: uiImage) .resizable() .frame(width: 126, height: 96) } }) } } .padding() } @State var indexOn = 0 var body: some View { HStack{ Button(action: { indexOn = (indexOn == 0) ? 2 : indexOn - 1 }) { Label("", systemImage: "arrowtriangle.left.fill") .font(.system(size: 50)) } Spacer() ScrollView { switch indexOn { case 0: createBackgroundGridView(for: firstSet, columns: columns) case 1: createBackgroundGridView(for: secondSet, columns: columns) case 2: createBackgroundGridView(for: thirdSet, columns: columns) case 3: createBackgroundGridView(for: thirdSet, columns: columns) default: createBackgroundGridView(for: firstSet, columns: columns) } } .frame(maxWidth: .infinity, maxHeight: .infinity) Spacer() Button(action: { indexOn = (indexOn == 2) ? 0 : indexOn + 1 }) { Label("", systemImage: "arrowtriangle.right.fill") .font(.system(size: 50)) } } } } Energy Use when app starts: Energy use after clicking for about 10 seconds: App UI:
0
0
16
4h
Attempt to present * on * from * while a presentation is in progress
Hi I'm new to Swiftui. I want to show a sheet and pass a var to it. In the case below when I tap on a list view it will popup then disappear. But subsequent taps will work as intended. Main view: struct ContentView: View { @State private var selectedMonth = 1 @State private var selectedYear = "2024" let months = [1,2,3,4,5,6,7,8,9,10,11,12] @State private var isShowing = false var body: some View { List { ForEach (months, id: \.self) { month in HStack { ViewList(month: month, year: selectedYear) } .onTapGesture { isShowing = true selectedMonth = month } .sheet(isPresented: $isShowing){ PopupView(month: selectedMonth, year: selectedYear) .presentationDetents([.large]) } } } .listRowSpacing(2) .listStyle(.grouped) } } ViewList: struct ViewList: View { var month: Int var year: String @State private var selectedMonthText = "Jan" var body: some View { VStack (alignment: .leading) { Text(selectedMonthText + " / " + year) .font(.headline) } .onAppear { switch month { case 01: selectedMonthText = "Jan" case 02: selectedMonthText = "Feb" case 03: selectedMonthText = "Mar" case 04: selectedMonthText = "Apr" case 05: selectedMonthText = "May" case 06: selectedMonthText = "Jun" case 07: selectedMonthText = "Jul" case 08: selectedMonthText = "Aug" case 09: selectedMonthText = "Sep" case 10: selectedMonthText = "Oct" case 11: selectedMonthText = "Nov" case 12: selectedMonthText = "Dec" default: selectedMonthText = "All" } } } } Then my popup: struct PopupView: View { @Environment(\.dismiss) var dismiss var month: Int var year: String @State private var selectedMonthText = "Jan" @State private var imageText = "plus" @State private var items = ["Cat", "Dog", "Bird", "Snake"] var body: some View { Button("Dismiss"){ dismiss() } Text(selectedMonthText + " / " + year) List { ForEach(items, id: \.self) {item in HStack { Text(item) Text("Fed on: ") Text(selectedMonthText) } } } .listRowSpacing(0) .listStyle(.inset) .onAppear { switch month { case 01: selectedMonthText = "Jan" case 02: selectedMonthText = "Feb" case 03: selectedMonthText = "Mar" case 04: selectedMonthText = "Apr" case 05: selectedMonthText = "May" case 06: selectedMonthText = "Jun" case 07: selectedMonthText = "Jul" case 08: selectedMonthText = "Aug" case 09: selectedMonthText = "Sep" case 10: selectedMonthText = "Oct" case 11: selectedMonthText = "Nov" case 12: selectedMonthText = "Dec" default: selectedMonthText = "All" } } } }
2
0
87
20h
Anime with TabView
In vision OS, the tab bar of TabView is outside the window by default. If I switch a page without TabView to a page that needs TabView in my program, the tab bar will suddenly appear on the left side of the screen without any animation. I hope it has an animation when it appears (such as easeIn, move). I tried it in Tab. Other animation-related modifiers such as animation are added under View, but there is no animation in the tab bar. Only the view in the tab has an animation effect, but this is not what I want. What I want is that the tab bar outside the window can have animation. What should I do?
1
0
95
8h
All SystemSoundID
In the AudioServicesPlaySystemSound function of AudioToolbox, you can enter the corresponding SystemSoundID to play some sound effects that come with the system. However, I can't be sure what sound effect each number corresponds to, so I want to know all the sound effects in visionOS and its corresponding SystemSoundID.
0
0
83
8h
Map behaves differently compared to MKMapView
Hey, I have a problem. I was using MKMapView in my app, and in the view where I had a background at the top of the screen, in the example it was Color.red, it extended all the way to the top of the screen. Now, I wanted to switch to the newer Map and I'm seeing an issue because I'm getting a navigation bar that cuts off my color as I indicated in the picture. Does anyone know why this is happening and if there's another way to achieve this? Steps to reproduce: Change MapView() to Map() to see difference import SwiftUI import MapKit @main struct TestAppApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { var body: some View { NavigationStack { ScrollView(.vertical) { Color.red .padding(.top, -200) .frame(height: 200) MapView().frame(minHeight: 300) // change this line to Map } .navigationTitle("Title") .navigationBarTitleDisplayMode(.large) } } } private typealias ViewControllerRepresentable = UIViewControllerRepresentable struct MapView: ViewControllerRepresentable { typealias ViewController = UIViewController class Controller: ViewController { var mapView: MKMapView { guard let tempView = view as? MKMapView else { fatalError("View could not be cast as MapView.") } return tempView } override func loadView() { let mapView = MKMapView() view = mapView } } func makeUIViewController(context: Context) -> Controller { Controller() } func updateUIViewController(_ controller: Controller, context: Context) { update(controller: controller) } func update(controller: Controller) { } } #Preview { ContentView() } I got: I want:
1
0
65
1d
How to replace tabBar with bottomBar with smooth animation in SwiftUI?
I am trying to replace the navigation tab bar with a custom bottom toolbar when a view enters edit mode. Currently, I am using the following code to achieve this: content .toolbar(isEditing ? .hidden : .visible, for: .tabBar) . toolbar(isEditing ? .visible : .hidden, for: .bottomBar) However, this results in a janky animation. When the bottom bar appears, it animates in above (in contrast to in place of) the tab bar, then "jumps" back down to the correct offset without animation. I had to workaround this by delaying the appearance of bottom bar by 0.3s. I am already using withAnimation(). Is this a bug or am I using the APIs incorrectly? Is there a more seamless way to achieve this switching effect other than delaying the bottom bar? Thanks!
0
0
63
1d
Confusing SwiftUI error log: "Mutating observable property after view is torn down has no effect"
Hey, I have a setup in my app that I am currently building, that uses @Observable router objects that hold the app's entire navigation state, so that I can easily set it globally and let SwiftUI show the appropriate views accordingly. Each view gets passed in such a router object and there is a global "app" router that the app's root view can access as an entry point: @Observable @MainActor final class AppRouter { static let shared = AppRouter() // Entry point used by the app's root view var isShowingSheet = false // Navigation state let sheetRouter = SheetRouter() // Router that's passed to the sheet view. This router could contain other routers for sheets it will show, and so on } @Observable @MainActor final class SheetRouter { // Example of a "nested" router for a sheet view var path = NavigationPath() var isShowingOtherSheet = false func reset() { path = .init() isShowingOtherSheet = false } } To open a sheet, I have a button like this: @Bindable var appRouter = AppRouter.shared // ... Button("Present") { appRouter.sheetRouter.reset() // Reset sheet router appRouter.isShowingSheet = true // show sheet } This seems to work perfectly fine. However, this produces tons of "error" logs in the console, whenever I open the sheet for a second time: Mutating observable property \SheetRouter.path after view is torn down has no effect. Mutating observable property \SheetRouter.path after view is torn down has no effect. Mutating observable property \SheetRouter.path after view is torn down has no effect. Mutating observable property \SheetRouter.path after view is torn down has no effect. Mutating observable property \SheetRouter.isShowingOtherSheet after view is torn down has no effect. These errors appear when calling the reset() of the sheet view's router before opening the sheet. That method simply resets all navigation states in a router back to their defaults. It's as if the sheetRouter is still connected to the dismissed view from the previous sheet, causing a mutation to trigger these error logs. Am I misusing SwiftUI here or is that a bug? It's also worth mentioning that these error logs do not appear on iOS 17. Only on iOS 18. So it might be a bug but I just want to make sure my usage of these router objects is okay and not a misuse of the SwiftUI API that the runtime previously simply did not catch/notice. Then I'd have to rewrite my entire navigation logic. I do have an example project to demonstrate the issue. You can find it here: https://github.com/SwiftedMind/PresentationBugDemo. I have also filed a feedback for this: FB14162780 STEPS TO REPRODUCE Open the example project. Open the sheet in the ContentView twice by tapping "Present" Close that sheet Open it again. Then the console will show these error logs from above. I'd appreciate any help with this. Cheers
1
2
91
2d
Map behaves differently compared to MKMapView
Hey, I have a problem. I was using MKMapView in my app, and in the view where I had a background at the top of the screen, in the example it was Color.red, it extended all the way to the top of the screen. Now, I wanted to switch to the newer Map and I'm seeing an issue because I'm getting a navigation bar that cuts off my color as I indicated in the picture. Does anyone know why this is happening and if there's another way to achieve this? Steps to reproduce: Change MapView() to Map() to see difference import SwiftUI import MapKit @main struct TestAppApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { var body: some View { NavigationStack { ScrollView(.vertical) { Color.red .padding(.top, -200) .frame(height: 200) MapView().frame(minHeight: 300) // change this line to Map } .navigationTitle("Title") .navigationBarTitleDisplayMode(.large) } } } private typealias ViewControllerRepresentable = UIViewControllerRepresentable struct MapView: ViewControllerRepresentable { typealias ViewController = UIViewController class Controller: ViewController { var mapView: MKMapView { guard let tempView = view as? MKMapView else { fatalError("View could not be cast as MapView.") } return tempView } override func loadView() { let mapView = MKMapView() view = mapView } } func makeUIViewController(context: Context) -> Controller { Controller() } func updateUIViewController(_ controller: Controller, context: Context) { update(controller: controller) } func update(controller: Controller) { } } #Preview { ContentView() } I got: I want:
0
0
68
2d
Saving SwiftData in Background Does Not Update @Query
I'm trying to use SwiftData for a new app after ~20 years of Core Data (and EOF before that). So while I'm new to SwiftData, I'm not new to Apple persistence frameworks. I've got a pretty typical workflow - need to load some JSON from the network, convert that into model objects. I've created an actor using the @ModelActor macro and I'm using that to do the network fetch and insert. I can set breakpoints in this code and see that it does indeed run and it's running on a non-main queue. That all seems fine. The problem is that my @Query powered variable in my SwiftUI user interface does not get updated when this data is loaded and saved as I would expect it to. I'm passing in the container to the actor using modelContext.container from the same modelContext that is powering the view / in the environment. My understanding was that like Core Data before it, the SwiftData framework was listening for the relevant notifications passed by the container/context, processing those and updating the UI but I can only see my data if I quit and relaunch the app. This seems like it should be a very common use case but I've not found much online. Not sure if that means I'm just doing something fundamentally wrong or what. Tested on both iOS 18 and 17 with the same results. Anyone else doing this successfully? What could I be doing wrong?
0
1
114
2d
SwiftUI Preview + Swift Packages Break App
I have a multi-platform app with the SwiftUI code a separate Swift Package. Any Views with SwiftUI Previews break the compilation of the app. Here's the error message I get in Xcode: Showing All Messages ld: warning: Could not parse or use implicit file '/Applications/Xcode-beta.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore.tbd': cannot link directly with 'SwiftUICore' because product being built is not an allowed client of it Undefined symbols for architecture arm64_32: "(extension in SwiftUI):DeveloperToolsSupport.Preview.init(_: Swift.String?, traits: DeveloperToolsSupport.PreviewTrait&lt;DeveloperToolsSupport.Preview.ViewTraits&gt;..., body: @Swift.MainActor @Sendable () -&gt; SwiftUI.View) -&gt; DeveloperToolsSupport.Preview", referenced from: static BitnessViews.$s12BitnessViews33_ABDBADF565C741E50A2A5746CE94FCD9Ll7PreviewfMf_15PreviewRegistryfMu_.makePreview() throws -&gt; DeveloperToolsSupport.Preview in BitnessViews.o ld: symbol(s) not found for architecture arm64_32 clang: error: linker command failed with exit code 1 (use -v to see invocation) Could not parse or use implicit file '/Applications/Xcode-beta.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore.tbd': cannot link directly with 'SwiftUICore' because product being built is not an allowed client of it Undefined symbol: (extension in SwiftUI):DeveloperToolsSupport.Preview.init(_: Swift.String?, traits: DeveloperToolsSupport.PreviewTrait&lt;DeveloperToolsSupport.Preview.ViewTraits&gt;..., body: @Swift.MainActor @Sendable () -&gt; SwiftUI.View) -&gt; DeveloperToolsSupport.Preview Linker command failed with exit code 1 (use -v to see invocation) Any thoughts as to what might be going on here?
1
0
83
2d
Microphone input in website in webview for swiftui
I have a website of a chatbot that also accepts microphone inputs and I embedded that into my swift and the everything other than the mic is working. I have included permission in the info file and here’s some of the code : import SwiftUI import WebKit import AVFoundation struct WebView: UIViewRepresentable { let url: URL class Coordinator: NSObject, WKUIDelegate, WKNavigationDelegate { var parent: WebView init(parent: WebView) { self.parent = parent } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(.allow) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler() })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler(true) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completionHandler(false) })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alert = UIAlertController(title: prompt, message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.text = defaultText } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler(alert.textFields?.first?.text) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completionHandler(nil) })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) { decisionHandler(.grant) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("Navigation error: \(error.localizedDescription)") } } func makeCoordinator() -> Coordinator { Coordinator(parent: self) } func makeUIView(context: Context) -> WKWebView { let webConfiguration = WKWebViewConfiguration() webConfiguration.allowsInlineMediaPlayback = true webConfiguration.mediaTypesRequiringUserActionForPlayback = [] let webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = context.coordinator webView.navigationDelegate = context.coordinator requestMicrophoneAccess() return webView } func updateUIView(_ webView: WKWebView, context: Context) { let request = URLRequest(url: url) webView.load(request) } func requestMicrophoneAccess() { AVAudioSession.sharedInstance().requestRecordPermission { granted in DispatchQueue.main.async { if granted { print("Microphone access granted") } else { print("Microphone access denied") } } } } func presentAlert(alert: UIAlertController) { if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let rootViewController = windowScene.windows.first?.rootViewController { rootViewController.present(alert, animated: true, completion: nil) } } }
0
0
101
2d
SwiftUI and SwiftData projects, textField gets focus, freezes, and takes 7000 milliseconds to focus
macOS 14.5、Xcode 15.4、iPhone OS 18.0 beta Open Xcode and create a new project. Select swiftUI for Interface, Swift for Language, and Swiftdata for Storage. After creating the project, open the ContentView.swift file,write the code @State var username: String = "" TextField("info", text: $username) .textFieldStyle(.roundedBorder) .disableAutocorrection(true) .textInputAutocapitalization(.never) Run the project on iPhone. textField gets focus, freezes, and takes 7000 milliseconds to focus
0
0
71
3d
SwiftUI Previews not working with Firebase in Xcode 16.0 beta
The SwiftUI previews have been working fine in Xcode 16.0 beta, but ever since I added Firebase into my app, I've been getting error with previews. CrashReportError: IshaanCord crashed IshaanCord crashed. Check ~/Library/Logs/DiagnosticReports for crash logs from your application. Process: IshaanCord[5651] Date/Time: 2024-07-04 19:29:51 +0000 Log File: <none> "Cannot preview in this file" Does anyone know how to fix this? Thank you.
1
0
121
3d
Vertical ScrollView Height and Paging Offset Issues in SwiftUI
Hi everyone, I'm currently working on an iOS app using SwiftUI, and I'm facing an issue with a vertical ScrollView. My goal is to have the ScrollView take up all the safe area space plus the top inset (with the bottom inset being an ultra-thin material) and enable paging behavior. However, I'm encountering two problems: The initial height of the ScrollView is too high (dragging the view (even without changing the page) adjusts the size). The paging offset of the ScrollView is incorrect (page views are not aligned). I’ve tried many things and combinations in desperation, including padding, safeAreaPadding, contentMargins, frame, fixedSize, containerRelativeFrame with callback, custom layout, and others, but nothing seems to work. If by any chance someone can help me find a solution, I’d greatly appreciate it. I suspect there are issues with the height defined by the ScrollView when some safe areas are ignored, leading to strange behavior when trying to set the height. It's challenging to explain everything in a simple post, so if someone from the SwiftUI team could look into this potential bug, that would be incredibly helpful. Thank you! import SwiftUI struct ScrollViewIssue: View { @State private var items: [(String, Color)] = [ ("One", .blue), ("Two", .green), ("Three", .red), ("Four", .purple) ] var body: some View { ZStack(alignment: .top) { ScrollView(.vertical) { VStack(spacing: 0) { ForEach(items, id: \.0) { item in ItemView(text: item.0, color: item.1) .containerRelativeFrame([.horizontal, .vertical]) } } } .printViewSize(id: "ScrollView") .scrollTargetBehavior(.paging) .ignoresSafeArea(edges: .top) VStack { Text("Title") .foregroundStyle(Color.white) .padding() .frame(maxWidth: .infinity) .background(Color.black.opacity(0.2)) Spacer() } } .printViewSize(id: "ZStack") .safeAreaInset(edge: .bottom) { Rectangle() .frame(width: .infinity, height: 0) .overlay(.ultraThinMaterial) } } } struct ItemView: View { let text: String let color: Color var body: some View { ZStack { RoundedRectangle(cornerRadius: 20) .fill(color.opacity(0.2)) .overlay( color, in: RoundedRectangle(cornerRadius: 20) .inset(by: 10 / 2) .stroke(lineWidth: 10) ) Text(text) } .printViewSize(id: "item") } } struct ViewSizeKey: PreferenceKey { static var defaultValue = CGSize() static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } extension View { func printViewSize(id: String) -> some View { background( GeometryReader { proxy in Color.clear .preference(key: ViewSizeKey.self, value: proxy.size) } .onPreferenceChange(ViewSizeKey.self) { value in print("\(id) size:\(value)") } ) } } #Preview { ScrollViewIssue() }
1
0
96
4d