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

SwiftUI Documentation

Posts under SwiftUI tag

2,333 Posts
Sort by:
Post not yet marked as solved
0 Replies
17 Views
Hi team, I'm running into the following issue, for which I don't seem to find a good solution. I would like to be able to drag and drop items from a view into empty space to open a new window that displays detailed information about this item. Now, I know something similar has been flagged already in this post (FB13545880: Support drag and drop to create a new window on visionOS) HOWEVER, all this does, is launch the App again with the SAME WindowGroup and display ContentView in a different state (show a selected product e.g.). What I would like to do, is instead launch ONLY the new WindowGroup, without a new instance of ContentView. This is the closest I got so far. It opens the desired window, but in addition it also displays the ContentView WindowGroup WindowGroup { ContentView() .onContinueUserActivity(Activity.openWindow, perform: handleOpenDetail) } WindowGroup(id: "Detail View", for: Reminder.ID.self) { $reminderId in ReminderDetailView(reminderId: reminderId! ) } .onDrag({ let userActivity = NSUserActivity(activityType: Activity.openWindow) let localizedString = NSLocalizedString("DroppedReminterTitle", comment: "Activity title with reminder name") userActivity.title = String(format: localizedString, reminder.title) userActivity.targetContentIdentifier = "\(reminder.id)" try? userActivity.setTypedPayload(reminder.id) // When setting the identifier let encoder = JSONEncoder() if let jsonData = try? encoder.encode(reminder.persistentModelID), let jsonString = String(data: jsonData, encoding: .utf8) { userActivity.userInfo = ["id": jsonString] } return NSItemProvider(object: userActivity) }) func handleOpenDetail(_ userActivity: NSUserActivity) { guard let idString = userActivity.userInfo?["id"] as? String else { print("Invalid or missing identifier in user activity") return } if let jsonData = idString.data(using: .utf8) { do { let decoder = JSONDecoder() let persistentID = try decoder.decode(PersistentIdentifier.self, from: jsonData) openWindow(id: "Detail View", value: persistentID) } catch { print("Failed to decode PersistentIdentifier: \(error)") } } else { print("Failed to convert string to data") } }
Posted
by
Post not yet marked as solved
0 Replies
18 Views
Is there a system deep link URI to the built in files app? I would like to direct users to my apps location in the files app. For example files://myApp The only exposed deep links for system I can find are the ones for mail, sms, FaceTime etc. Thank you (tag used for post was because I couldn’t find a deep link tag)
Posted
by
Post not yet marked as solved
1 Replies
45 Views
Is it possible to switch to a new View without using NavigationStack or NavigationLink or NavigationView? I know I can do it with a Bool, which either shows the second view, or the first, and then toggles the Bool. But can't I do something like this? Which obviously doesn't work. struct BasicButton: View { var buttonLabel = "Create User" var body: some View { Button { CreateUser() //another SwiftUI view, not a function } label: { Text(buttonLabel) } } }
Posted
by
Post not yet marked as solved
0 Replies
30 Views
When I try to share a image of a component using the ImageRenderer, the type is not .png while sharing the image created using ShareLink (The type is .jpeg for some reasons...) My code looks like this: ShareLink( "Share", item: ( ImageRenderer( content: shareView.frame( width: 420, height: 520 ) ).uiImage?.pngData() )!, preview: SharePreview( "Share Preview", image: ( ImageRenderer( content: shareView.frame( width: 420, height: 520 ) ).uiImage?.pngData() )! ) ) Also the image shared is always in low resolution, if anyone knows what to do in this case let me know! Any helps will be appreciated!
Posted
by
Post not yet marked as solved
0 Replies
42 Views
I have a Canvas inside a ScrollView on a Mac. The Canvas's size is determined by a model (for the example below, I am simply drawing a grid of circles of a given radius). Everything appears to works fine. However, I am wondering if it is possible for the Canvas rendering code to know what portion of the Canvas is actually visible in the ScrollView? For example, if the Canvas is large but the visible portion is small, I would like to avoid drawing content that is not visible. Is this possible? Example of Canvas in a ScrollView I am using for testing: struct MyCanvas: View { @ObservedObject var model: MyModel var body: some View { ScrollView([.horizontal, .vertical]) { Canvas { context, size in // Placeholder rendering code for row in 0..<model.numOfRows { for col in 0..<model.numOfColumns { let left: CGFloat = CGFloat(col * model.radius * 2) let top: CGFloat = CGFloat(row * model.radius * 2) let size: CGFloat = CGFloat(model.radius * 2) let rect = CGRect(x: left, y: top, width: size, height: size) let path = Circle().path(in: rect) context.fill(path, with: .color(.red)) } } } .frame(width: CGFloat(model.numOfColumns * model.radius * 2), height: CGFloat(model.numOfRows * model.radius * 2)) } } }
Posted
by
Post not yet marked as solved
0 Replies
39 Views
I have a swiftui iPhone app running on the "iOS Apps on Mac" simulator. What I'm trying to do is get a notification when the window size changes, but nothing seems to work. I have tried .onReceive(NotificationCenter.default.publisher(for: UIContentSizeCategory.didChangeNotification)) { _ in updateStuff() } I also tried .onAppear() { updateStuff() } but neither seems to get called any suggestions ?
Posted
by
Post not yet marked as solved
1 Replies
58 Views
I'm fairly new to SwiftUI and when I create a new file in a project and make edits to it, when in the process of commiting the changes to my local repository, i notice that Xcode is creating duplicate files of all my files with changes, including the main app file. They each have a '._' prefix on them. When I view the changes in these files the text is unrecognizable, and i can't locate them in finder. They seem to get in teway of trying to merge branches in my repository ._ContentView -----END SIGNED MESSAGE-----git_revwalk_new(&walk, repo)NSString *gitRepositoryIdentifier(git_repository *)git_revwalk_push_head(walk)gitErrorgit_commit_lookup(&commit, repo, &revisionOID)git_commit_tree(&tree, commit)git_mailmap_from_repository(&mailmap, repo)git_remote_list(&remotes, repo)git_remote *lookupRemote(git_repository *, DVTSourceControlRemoteRepository *__strong, BOOL, NSString *__autoreleasing *, NSError *__autoreleasing *)git_remote_lookup(&remote, repo, remoteName)status--porcelain-[DVTSourceControlGitPlugInPrimary(Status) _filesAndStatusOfWorkingCopy:withRemoteStatus:]git_status_list_new(&statusList, repo, &statusOptions)Silent error with libgit operation (%s)git_repository_head(&head, repo)git_branch_upstream(&upstreamBranch, head)git_merge_base(&mergeBase, repo, git_reference_target(head), git_reference_target(upstreamBranch))git_commit_lookup(&baseCommit, repo, &mergeBase)git_commit_tree(&baseTree, baseCommit)git_reference_peel((git_object **)&upstreamTree, upstreamBranch, GIT_OBJ_TREE)git_diff_tree_to_tree(&treeDiff, repo, baseTree, upstreamTree, &diffopts)%@...%@-[DVTSourceControlGitPlugInPrimary(Status) filesAndStatusOfWorkingCopy:sourceBranch:targetBranch:completionBlock:]git_reference_lookup(&sourceReference, repo, sourceBranchName)git_reference_lookup(&targetReference, repo, targetBranchName)git_reference_name_to_id(&source_tree_oid, repo, source_ref_name)git_reference_name_to_id(&target_tree_oid, repo, target_ref_name)git_reference_peel((git_object **)&sourceTree, sourceReference, GIT_OBJ_TREE)git_reference_peel((git_object **)&targetTree, targetReference, GIT_OBJ_TREE)diff--name-status git_merge_base(&merge_base, repo, &source_tree_oid, &target_tree_oid)--no-color--stagedcore.excludesfileB24@?0@8@"NSDictionary"16~/%@.gitignore_globalgit_config_set_string(levelConfig, "core.excludesfile", ignorePath.fileSystemRepresentation)-[DVTSourceControlGitPlugInPrimary(Ignore) setIgnoredFiles:completionBlock:]%s index.lockstashsave-u-[DVTSourceControlGitPlugInPrimary(Stash) stashChangesOfWorkingCopy:includingUnversioned:message:completionBlock:]i32@?0Q8r*16r^{git_oid=[20C]}24Could not locate stash identifier from revisionv24@?0q8@"NSError"16-[DVTSourceControlGitPlugInPrimary(Stash) _deleteStash:stashIdentifier:completionBlock:]git_stash_drop(repo, stashIdentifier)-[DVTSourceControlGitPlugInPrimary(Stash) _stashIdentiferFromRevision:workingCopy:completionBlock:]git_stash_foreach(repo, stashCallback, (__bridge void *)stashBlock)-[DVTSourceControlGitPlugInPrimary(Stash) applyStashInWorkingCopy:stash:completionBlock:]git_stash_apply(repo, stashIndex, &options)git_repository_index(&index, repo)show-p%ld%ld.patchCouldn't create temporary path for stash '%ld'Couldn't write data to path '%@'v16@?0@"DVTSourceControlHistoryResultType"8DVTSourceControlCMSClassErrorCodeKeyCMS Module Error with code %d.SecTrust could not validate the signing certificate.Signature is invalid or malformed.No remote repository specified for fetch.Specified local repository has no on-disk URL set.--jobs=%lufetch--atomic--quiet--no-recurse-submodulesv16@?0@"NSData"8debug1%@v24@?0@"NSString"8^B16ssh: Could not resolve hostnamePermission deniedHost key verification failedCould not read from remote repositoryUnknown error while fetching remote changes. Make sure the remote is set up correctly and that you have access to it.git_remote_fetch(remote, NULL, &fetchOptions, NULL)-[DVTSourceControlGitPlugInPrimary(Update) fetchFromRemoteRepositoryUsingLibGit:repo:includeTags:prune:error:]Failed to locate remote for URL '%@'-[DVTSourceControlGitPlugInPrimary(Update) downloadUpdatesFromRemoteRepository:toRepository:removeDeletedLocations:progressIdentifier:completionBlock:]-[DVTSourceControlGitPlu I notice that when following online tutorials on the subject of source control, they don't show any files like these. What am I missing?
Posted
by
Post not yet marked as solved
0 Replies
46 Views
When adding a Map using the MapKit this changes the appearance of the TabBar appearance, specifically gives the toolbar a translucent background with a shadow; the default iOS style. I have tried adding the following modifier to the Map .toolbarBackground(Color("White"), for: .navigationBar) But the navigation toolbar still has a shadow, and the TabBar has the default translucent background colour with shadow. Root init() { // this is not the same as manipulating the proxy directly let appearance = UINavigationBarAppearance() // this overrides everything you have set up earlier. appearance.configureWithTransparentBackground() appearance.shadowColor = .clear //In the following two lines you make sure that you apply the style for good UINavigationBar.appearance().scrollEdgeAppearance = appearance UINavigationBar.appearance().standardAppearance = appearance UITabBar.appearance().barTintColor = UIColor.white) UITabBar.appearance().backgroundColor = UIColor.white) UITabBar.appearance().shadowImage = UIImage() UITabBar.appearance().backgroundImage = UIImage() UINavigationBar.appearance().isTranslucent = false UIToolbar.appearance().backgroundColor = UIColor.white) UIToolbar.appearance().isTranslucent = false UIToolbar.appearance().setShadowImage(UIImage(), forToolbarPosition: .any) } struct MainView: View { var body: some View { TabView { ContentView() .tabItem { Label("Menu", systemImage: "list.dash") } } } } The Tabbar has a solid white colour with no shadow, as well as navigation bars. Content View struct ContentView: View { var body: some View { NavigationStack() { NavigationLink(destination: MapView()) { Text("Hello, World!") } } .navigationTitle("Content") } } MapView struct MapView: View { @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)) var body: some View { Map(coordinateRegion: $region) .mapControlVisibility(.hidden) .allowsHitTesting(false) .frame(maxWidth: .infinity) .frame(height: 414) .clipped() } } I have looked through the documentation but could not find anything. https://developer.apple.com/documentation/mapkit/map
Posted
by
Post not yet marked as solved
1 Replies
85 Views
Hello can I have some help on how to fix the code. Please can you tell me what to adjust to make the code work.(it was from a YouTube video and have compared it as close as possible and still doesn't work. 'No exact matches in call to initialiser' error at the work 'Group {' import SwiftUI struct ContentView: View { @State var text: Array&lt;String&gt; = [] @State var showsheet = false @State var textitemtemp = "" var body: some View { NavigationView { Group { if text.count &lt;= 1 { Text("no items") } else { List { ForEach((1...text.count-1, id: \.self), {i in Text(text[i]) .contextMenu { Button(action: { text.remove(at: i) }, label: { Label ("Delete", systemImage: "delete.left") }) } } ) } .navigationTitle("Idea Book") .toolbar { Button(action: { showsheet.toggle() textitemtemp = "" }, label: { Image(systemName: "plus") } ) } .onChange(of: text) { save() load() } .onAppear() { save() load() } } .refreshable { save() load() } .sheet(isPresented: $showsheet) { NavigationView { List { TextField("Item", text: $textitemtemp) } .navigationTitle("Add an Idea") .toolbar { Button("add") { text.append(textitemtemp) showsheet.toggle() } } } } func save() -&gt; Void { let temp = text.joined(separator: "/[split]/") let key = UserDefaults.standard key.set(temp, forKey: "text") } func load() -&gt; Void { let key = UserDefaults.standard let temp = key.string(forKey: "text") ?? "" let temparray = temp.components(separatedBy:"/[split]/") text = temparray } } #if DEBUG ContentView() #endif } } }
Posted
by
Post not yet marked as solved
0 Replies
70 Views
Environment: Xcode 15.3.0. MacOS 14.4.1 (23E224) Depl. Target: iOS 17.2 Supported Destinations: iPhone Notes: Using SwiftData. Shared code in the Persistency library. Hello everyone, I am writing here after really trying everything I can to understand what is going on. I have a widget bundle composed by two different widgets, defined as following: import WidgetKit import SwiftUI import SwiftData @main struct MyWidgetBundle: WidgetBundle { @WidgetBundleBuilder var body: some Widget { MyWidget() MylMediumWidget() } } They have 2 different providers (since they need different data). The are then defined as following: import SwiftUI import WidgetKit import Persistency import SwiftData struct MyMediumWidget: Widget { let kind: String = "MyStatus" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: MyEntryProvider()) { entry in MyMediumWidgetView(entry: entry) .containerBackground(Color.Theme.background, for: .widget) } .supportedFamilies([.systemMedium, .systemLarge]) .configurationDisplayName("My Reminder Medium") .description("Bla bla bla") } } And import WidgetKit import SwiftUI import Persistency struct MyWidget: Widget { let kind: String = "MyStatus" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: SmallEntryProvider()) { entry in MyWidgetGroup(entry: entry) .containerBackground(Color.Theme.background, for: .widget) } .supportedFamilies([.systemSmall, .accessoryCircular]) .configurationDisplayName("My Reminder Small") .description("Bla bla 2") } } struct ActiveMealWidgetGroup: View { var entry: SmallEntryProvider.Entry @Environment(\.widgetFamily) var family var body: some View { switch family { case .systemSmall: MySmallWidgetView(entry: entry) case .accessoryCircular: MyAcessoryCircularWidgetView(entry: entry) default: Text("Unsupported size") } } } Note: They belong to 1 single Widget Extension for iOS. For some reason I have VERY strange behaviors in widgets with the following code. Example: When I insert the medium size, it is randomly removed from the home screen. For example, I add the small and the medium. After 3h, the medium is gone. If I try to add the widgets in mac os (readying from phone, the app is only for iOS), only the small appears. No medium and large are shown. If I try to compile the widget scheme selecting systemLarge in the xcode argument, I have an error saying: "Request widget family (systemLarge) is not supported by this widget kind (MyStatus)" UserInfo={NSLocalizedDescription=Request widget family (systemLarge) is not supported by this widget kind (MyStatus)}} What is going on? Seems my widgets are really wrongly configured, but I can't see where the issue can be. Hope someone can help me. Best Regards
Posted
by
Post not yet marked as solved
2 Replies
67 Views
I have added a button in UIController: let button = UIButton(type: .custom) button.setTitle("test", for: .normal) button.addTarget(self, action: #selector(addToSiri), for: .touchUpInside) self.view.addSubview(button) Then using it in SwiftUI HStack { Controller() }.frame(maxWidth:.infinity, idealHeight: 60) And then using swiftUI in UIHostingController: let vc = UIHostingController(rootView: SwiftUIView()) But when I tap the button, the addToSiri is never called. I don't know why.
Posted
by
Post not yet marked as solved
0 Replies
53 Views
Hi, By default when selecting an item from a list in details panel it doesn't close how to make it close or hide by default ? Kindest Regards
Posted
by
Post marked as solved
2 Replies
68 Views
Hi, How to catch the event when details panel of a SplitView shows and get hidden, like when split is 2 columns and when its details only ? Kindest Regards
Posted
by
Post not yet marked as solved
0 Replies
49 Views
Hello everyone, I have a SwiftUI application with a view containing a MapKit map as UIViewRepresentable. I'm experience the following issue with regionDidChangeAnimated that seems related to MapKit itself as I was able to reproduce it also on another application I'm developing. The problem is that regionDidChangeAnimated is not getting called when zooming in or out, but it's getting called for other gestures, like panning and moving the map. This is what I noticed: I zoom in/out on the map regionWillChangeAnimated is called I release my fingers from the map regionDidChangeAnimated is NOT called If I move a bit the map -> regionDidChangeAnimated is called ( for the previous touch ), then regionWillChangeAnimated related to the new touch is called, regionDidChangeAnimated for the new touch is called. So it looks like when zooming in/out, regionDidChangeAnimated is lagging and not called until a new touch happens. Did you ever experienced this behavior? Thank you in advance for your support
Post not yet marked as solved
3 Replies
121 Views
I am trying to create an iOS app where I need to immediately know when the iPhone is unlocked. Let's say I want to print a log on the Xcode console whenever the phone is unlocked. From my app, how do I detect if the phone is unlocked? Some code pointers will be highly appreciated. I am a newbie in iOS/APP development. It should work even if my app is not running. Is it even possible to do so?
Posted
by
Post not yet marked as solved
3 Replies
68 Views
Hello, I use Preview to quickly test functionalities. However I found that the unified logging does not output to Preview console. So I had to do both log.debug and print. Is there a way to enable logging to Preview console?
Posted
by
Post not yet marked as solved
0 Replies
82 Views
It seems like this may have been an issue for a while based on what I've seen, but I have added a toolbar item to a textfield keyboard and it doesn't show. The only way I can get it to show is by opening the keyboard, typing something, closing the keyboard, and then reopening it. Anyone have a workaround for this? It's like Apple purposely wants to make it difficult to close the keyboard. TextField("Something here...", text: $text, axis: .vertical) .multilineTextAlignment(.leading) .toolbar { ToolbarItemGroup(placement: .keyboard, content: { Button("Close") { } }) }
Posted
by
Post not yet marked as solved
0 Replies
36 Views
I'm developing an Apple TV OS app using SwiftUI. I'm encountering an issue with the color of the tab item. I want the color of the tab item to turn green when focused; for instance, when the tab item is selected, its background color should be green. Below is my current code, but it's not working. I've tried several other approaches, but none have worked. struct ContentView: View { @State private var selectedTab = 0 var body: some View { ZStack(alignment: .topLeading){ TabView(selection: $selectedTab) { HomeView() .tabItem { AppColors.gradientColor1 Label("Home", image: "home-dash") } .tag(0) ProductsView() .tabItem { Label("Products", image: "open box-search") } .tag(1) SearchView() .tabItem { Label("Search", image: "search") } .tag(2) } .accentColor(Color.green) .background(.black) Image("amazontabbarlogo") } } }
Posted
by