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

SwiftUI Documentation

Posts under SwiftUI tag

2,335 Posts
Sort by:
Post not yet marked as solved
0 Replies
51 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 RileyDev.
Last updated
.
Post not yet marked as solved
4 Replies
460 Views
TabView { SummaryView() .toolbar(.hidden, for: .tabBar, .bottomBar) .tabItem { Text("Title.Summary") } .tag(TabItems.summary) CalendarView() .toolbar(.hidden, for: .tabBar, .bottomBar) .tabItem { Text("Title.Calendar") } .tag(TabItems.calendar) EventTypeView() .toolbar(.hidden, for: .tabBar, .bottomBar) .tabItem { Text("Title.EventType") } .tag(TabItems.group) LectureView() .toolbar(.hidden, for: .tabBar, .bottomBar) .tabItem { Text("Title.Lecture") } .tag(TabItems.lecture) NotificationView() .toolbar(.hidden, for: .tabBar, .bottomBar) .tabItem { Text("Title.Notifications") } .tag(TabItems.notification) } Tabbar is hidden when first opened but tabbar is appeared when I change tab selection. I tested it on iOS 17.1, iOS 17.4, and this bug is only appeared in iOS 17.4.
Posted
by LeeJaeho.
Last updated
.
Post marked as solved
2 Replies
70 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 Last updated
.
Post not yet marked as solved
1 Replies
88 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<String> = [] @State var showsheet = false @State var textitemtemp = "" var body: some View { NavigationView { Group { if text.count <= 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() -> Void { let temp = text.joined(separator: "/[split]/") let key = UserDefaults.standard key.set(temp, forKey: "text") } func load() -> Void { let key = UserDefaults.standard let temp = key.string(forKey: "text") ?? "" let temparray = temp.components(separatedBy:"/[split]/") text = temparray } } #if DEBUG ContentView() #endif } } }
Posted Last updated
.
Post not yet marked as solved
4 Replies
130 Views
I already filed feedback FB13777941 for this, but wanted to ask if anyone has the same problem, since I can't find anything on google or SO. I created a new package in Xcode (15.3) and added this to it: import SwiftUI struct Test: View { var body: some View { Text("Hello world") } } #Preview { Test() } The package builds, tests can run. Previews don't work. This is more or less the error I get from the diagnostics button (formatted for readability): LoadingError: failed to load library at path ”PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/PACKAGE_NAME_63097C4A372B9C87_PackageProduct”: Optional(dlopen(PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/PACKAGE_NAME_63097C4A372B9C87_PackageProduct, 0x0000): tried: 'PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (no such file), 'PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (mach-o file, but is an incompatible architecture (have 'arm64', need 'arm64e')), '/System/Volumes/Preboot/Cryptexes/OSPATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (no such file), 'PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (mach-o file, but is an incompatible architecture (have 'arm64', need 'arm64e')), 'PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/Versions/A/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (no such file), 'PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/Versions/A/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (mach-o file, but is an incompatible architecture (have 'arm64', need 'arm64e')), '/System/Volumes/Preboot/Cryptexes/OSPATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/Versions/A/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (no such file), 'PATH_TO_DERIVED_DATA/Build/Intermediates.noindex/Previews/macos/PACKAGE_NAME/Products/Debug/PackageFrameworks/PACKAGE_NAME_63097C4A372B9C87_PackageProduct.framework/Versions/A/PACKAGE_NAME_63097C4A372B9C87_PackageProduct' (mach-o file, but is an incompatible architecture (have 'arm64', need 'arm64e'))) I don't remember ever having this problem. The arm64 vs arm64e makes no sense to me - why would Xcode get that wrong... and only for previews? I've tried restarting, deleting derived data, the usual rain dances. Any ideas?
Posted
by Aurelian.
Last updated
.
Post not yet marked as solved
2 Replies
70 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 WWWang.
Last updated
.
Post not yet marked as solved
1 Replies
176 Views
I've been trying to follow the "Supporting Continuity Camera in Your Mac App" article to implement the "Import from iPhone or iPad" menu for my MacOS app. I've been able to replicate most of the article in a test AppKit application but cannot do the same in my SwiftUI application. I'm not sure how to get the "NSMenuItemImportFromDeviceIdentifier" identifier into a SwiftUI Menu or create a NSMenu with a NSMenuItem for a SwiftUI app. I'm also not sure how to handle receiving the image in the SwiftUI environment. Any advice you might have is appreciated. Thanks!
Posted Last updated
.
Post not yet marked as solved
0 Replies
74 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 Last updated
.
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 Last updated
.
Post not yet marked as solved
0 Replies
53 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
Posted Last updated
.
Post not yet marked as solved
0 Replies
40 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 Rajatalha.
Last updated
.
Post not yet marked as solved
0 Replies
85 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 Xavier-k.
Last updated
.
Post not yet marked as solved
0 Replies
88 Views
I was following the Swiftui tutorial at section 6 (https://developer.apple.com/tutorials/swiftui/creating-and-combining-views) to use a circle image to create an overlapping effect on the map. Turns out that when using a GeometryReader, the bottom padding was not working at all: VStack{ MapView().frame(height:300) CircleImage() .offset(y: -130) .padding(.bottom, -130) VStack(alignment:.leading){ Text( "Turtle Rock" ) .font( .title ) HStack { Text( "Joshua Tree National Park" ) .font( .subheadline ) Spacer() Text( "California" ) .font( .subheadline ) } }.padding(/*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/) } This is the code for the CicleImage view: GeometryReader(content: { geometry in let _ = print( geometry.size.width ) AsyncImage( url: URL( string: "https://cms.rationalcdn.com/v3/assets/blteecf9626d9a38b03/bltf5486c52361f2012/6144fafd39dff133fc23de9f/img-ios.png" ) ) .frame(width: geometry.size.width) .clipShape( Circle() ).overlay{ Circle().stroke( .white, lineWidth: 4 ) }.shadow( radius: 7 ) })
Posted
by miguelg97.
Last updated
.
Post marked as solved
1 Replies
110 Views
Hello everyone, I'm just getting started with Swift and I'm in a bit of a knot here. Code below: `if codeSent { TextField("6 Digit Code", text: $code) Divider() Button("Verify") { print("verify...") if code.count == 6 { cloud(fun: "customSmsAuth", cloudData: [ "code": code, "phoneNumber": phoneNumber ], completion: { resData in let res = resData["res"] as? Int if res == 1 { let customToken = resData["customToken"] Auth.auth().signIn(withCustomToken: customToken) { user, error in } } else { print("An error occured...") } }) } else { print("invalid code...") } }.padding() }` `else { HStack { Button("+26") { print("phone code...") } TextField("Phone Number", text: $phoneNumber) } Divider() Button("Send Code") { print("send code...") if phoneNumber.count == 10 { cloud(fun: "sendSms", cloudData: ["phoneNumber" : "+26"+phoneNumber], completion: { resData in let res = resData["res"] as? Int if res == 1 { codeSent = true } else { print("An error occured...") } }) } else { print("Invalid phone number...") } print(phoneNumber) }.padding() }` I'm trying to setup a simple phone based authentication with firebase. Any pointer where I'm going wrong will be appreciated. Thanks.
Posted Last updated
.
Post not yet marked as solved
2 Replies
142 Views
Hello. I've been looking all over this forum and stack and done some internet searches but unfortunately have found nothing to assist in fixing an error I'm receiving on my project in Xcode. Every view shows an error identical to the one shown above, only with that specific file name displayed instead. When I go to fix the error, this is the error detail displayed: == PREVIEW UPDATE ERROR: LinkDylibError: Failed to build TabBar.swift Linking failed: linker command failed with exit code 1 (use -v to see invocation) ld: warning: search path '/Applications/Xcode.app/Contents/SharedFrameworks-iphonesimulator' not found ld: unsupported mach-o filetype (only MH_OBJECT and MH_DYLIB can be linked) in '/Users/brycemchose/Library/Developer/Xcode/DerivedData/Service_Square_App-dnblqgabcrxprhaizjtkcvouyzln/Build/Intermediates.noindex/Previews/iphonesimulator/Service Square App/Products/Debug-iphonesimulator/Service Square.app/Service Square' clang: error: linker command failed with exit code 1 (use -v to see invocation) Note that I can run the app successfully to a simulator or to my iPhone, but cannot see the preview within the Xcode canvas. I've been blindly developing the last two app updates, pushing the changes to the simulator and then tweaking the code based on the simulated version. I can keep doing this for a little while but it is significantly slower and more difficult, especially to fix small bugs and make tiny changes, so I'd really like to see if anyone has an idea for how I can get the preview back to being properly displayed. I'm brand new to this whole thing and have no idea how to fix this issue, so I'd be really grateful if someone with more experience could offer some suggestions! Thanks in advance! :)
Posted Last updated
.
Post marked as solved
2 Replies
106 Views
Hi everyone I'm new to swiftui and I'm trying to understand the reason that allows swiftui to call a VStack or any other container view without parentheses as in: struct ContentView: View { var body: some View { VStack { Text("sth"); } } } After looking into the swift docs, it was clear as in any other programming language that instantiating a class/structure is made by calling the entity with its parentheses, an even passing some parameters if possible. Isn't should be the case for placing view components in the body computer property? So far my mind keeps telling me that the syntax should follow this convention struct ContentView: View { var body: some View { VStack() { Text("sth"); } } } At which concept should I look into for further clarifications All the best.
Posted
by miguelg97.
Last updated
.
Post not yet marked as solved
0 Replies
75 Views
I'm having issues with a Lazyvgrid displaying images after the screen orientation changes ( either from horizontal to portrait, or the reverse ) What happens is the images are not sized correctly. If 2 column , I see 1/3 of column 1 and the image in column 2 takes 2/3 of the screen width. Similar issues with 3 or 6 column layout. The Lazyvgrid is inside a ScrollView and thats inside a Tabview. I'v tried to trick an update by changing the column layout, the content mode (fit/fill) of the images, etc. but so far nothing has worked. Any suggestions ?, anyway to invalidate a lazyvgrid and have swiftui rebuild it ? Thanks.
Posted Last updated
.
Post not yet marked as solved
2 Replies
358 Views
I have created a tip with a parameter (Bool) I have tried to set it to true in a sheet which is presented modally over the view which should present the popover tip. After the sheet gets dismissed the popover tip is never presented. If I restart the app, the popover tip appears. Is there any way to trigger the presentation of a popover tip manually? I have created a little demo app to demonstrate my problem: Setup TipKit on app start: import SwiftUI import TipKit @main struct TipKitDemoApp: App { var body: some Scene { WindowGroup { ContentView() .task { try? Tips.configure() } } } } Simple tip: import Foundation import TipKit struct DemoTip: Tip { @Parameter static var enabled: Bool = false var title: Text { Text("Demo Tip") } var rules: [Rule] { [ #Rule(Self.$enabled) { $0 == true } ] } } Content view which includes the popover tip and displays the sheet where the tip can be enabled: import SwiftUI struct ContentView: View { @State private var presentDetail = false let demoTip = DemoTip() var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") .popoverTip(demoTip) Button("Present Details") { presentDetail.toggle() } } .padding() .sheet(isPresented: $presentDetail) { DetailView() } } } In the detail view the tip gets enabled, but if I dismiss this view, the tip only appears after I restart the app: import SwiftUI struct DetailView: View { @Environment(\.dismiss) private var dismiss var body: some View { Button("Enable demo tip") { DemoTip.enabled = true } Button("Dismiss") { dismiss() } } }
Posted
by patrick.
Last updated
.
Post marked as solved
1 Replies
135 Views
Hi, I'm developing an app using SwiftUI for both iOS and Mac OS and use onOpenURL to handle external links. However, this doesn't seem to work after switching to a single window app on Mac OS. This code works: WindowGroup { Text("Hi").onOpenURL { url in print("Open URL", url) } } But this doesn't: Window("My App", id: "my_app") { Text("Hi").onOpenURL { url in print("Open URL", url) } } Anyone knows a workaround? Thanks!
Posted Last updated
.
Post not yet marked as solved
1 Replies
47 Views
Hello, I'm working on a Swift/SwiftUI project, which is basically finished and everything was working well when I was doing it on macOS Monterey/Xcode 14.0.1, but since I upgraded to macOS Sonoma/Xcode 15.3, some issues have appeared from nowhere, without me doing any changes to the code in the meantime. Among these issues, I made a Drag Gesture (swipe up) on a ZStack, to navigate from a view to another. As I just said, like the rest it was initially working but it doesn't work anymore since my last macOS update and I didn't change anything. Here is the code related to it: .gesture( DragGesture() .onEnded { gesture in if gesture.translation.height < -50 { showGalleryView = true } } ) I tried to find the origin of the problem by doing prints, and I had the confirmation that the gesture is detected and the value of showGalleryView (which is a @State/@Binding variable) is indeed changed to true. But it doesn't have any effect, it stays on the initial view. Here are the results when I include the prints in the code above: I don't understand if there is a problem elsewhere in my code or if the problem is caused by something like a parameter in Xcode or the macOS update. Any ideas? Thanks.
Posted Last updated
.