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

Is it possible to retrieve optional @EnvironmentObject
I'm trying to develop an iOS app with SwiftUI supporting iOS15 and above and then I encounter with this issue. I have a SwiftUI view and call this view from multiple different UI flows. So I want to provide different environment objects depending which flow it is in. I want them optional because depending which environment object I am able to retrieve, I want to modify properties of those environment objects to trigger UI updates. (expect to use "if let" check for optional binding) Inside that view, I want to retrieve those environment objects as optionals but I can't use @EnvironmentObject because is expects conforming ObservableObject protocol. I also tried to use EnvironmentKey protocol to define custom optional types but this time Xcode gives error as: "Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs)" I really wonder If I am able to reach an optional environment object for iOS15. Note: I know that with Observation framework I may be able to get optional environment object but I have to update my supported iOS level beginning from iOS17 for the app which I can't do right now.
2
0
97
1w
SwiftUI: How to blend between UIImages without pulsating/pumping effect?
I want to smootlhy blend two or more UIImages without pulsating/pumping effect but cannot achieve this. I have created a simple example code to visualize my issue. Two UIImages with exactly the same content ("gear") are initialized. The images are then manipulated via "func resizeImage()" with: UIGraphicsBeginImageContext() defer { UIGraphicsEndImageContext() } draw(in: CGRect()) This custom draw: (in:) is important for me as in my app there is a lot of custom drawing logic. In the body I use a PhaseAnimator to animate through the different stages of my custom animation. The result is always a pulsating/pumping effect which is unwanted. If the shape of two blended UIImages is exactly the same, there should not be any noticeable difference, especially no intensity change. How to get a smooth blend without pulsating/pumping effect? Any help appreciated. import SwiftUI struct ContentView: View { @State var widgetSize: CGFloat = 128 let img1 = UIImage(systemName: "gear")! let img2 = UIImage(systemName: "gear")! func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight)) image.draw(in: CGRectMake(0, 0, newWidth, newHeight)) guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage(systemName: "questionmark")! } UIGraphicsEndImageContext() return newImage } var body: some View { PhaseAnimator([1, 2]) { phase in // This is just for demonstration purposes // I have two or more UIImages that I want to smootlhy blend // The UIImages are created with image.draw // the result is a pulsating animation but I would expect // a smooth blend over with no noticable change when there are two // UIImages with identical content let i1 = self.resizeImage(image: img1, newWidth: widgetSize) let i2 = self.resizeImage(image: img2, newWidth: widgetSize) VStack { Image(uiImage: phase == 1 ? i1 : i2) .renderingMode(.template) .foregroundStyle(.white) .background(.black) Spacer() } } } } #Preview { ContentView() }
1
0
118
1w
Unable to display contextMenu
This is a visionOS App. I added contextMenu under a combination view, but when I pressed the view for a long time, there was no response. I tried to use this contextMenu in other views, which can be used normally, so I think there is something wrong with this combination view, but I don't know what the problem is. I hope you can remind me. Thank you! Views with problems: struct NAMEView: View { @StateObject private var placeStore = PlaceStore() var body: some View { ZStack { Group { HStack(spacing: 2) { Image(systemName: "mappin.circle.fill") .font(.system(size: 50)) .symbolRenderingMode(.multicolor) .accessibilityLabel("your location") .accessibilityAddTraits([.isHeader]) .padding(.leading, 5.5) VStack { Text("\(placeStore.locationName)") .font(.title3) .accessibilityLabel(placeStore.locationName) Text("You are here in App") .font(.system(size: 13)) .foregroundColor(.secondary) .accessibilityLabel("You are here in App") } .hoverEffect { effect, isActive, _ in effect.opacity(isActive ? 1 : 0) } .padding() } } .onAppear { placeStore.updateLocationName() } .glassBackgroundEffect() .hoverEffect { effect, isActive, proxy in effect.clipShape(.capsule.size( width: isActive ? proxy.size.width : proxy.size.height, height: proxy.size.height, anchor: .leading )) .scaleEffect(isActive ? 1.05 : 1.0) } } } }
1
0
184
1w
StateObject unexpectedly init twice
Environment (Simulator & Device): iOS 17.5.1 iOS 16.7 iOS 18.0 beta 3 Steps to Reproduce: Build and run On the main screen, tap “First”. Then tap “Second”. Observed Behavior: On iOS 17.5.1, the StateObject attached to DetailView is initialized twice. The expected behavior is that the StateObject should be initialized only once. On iOS 16.7, the StateObject is initialized only once, as expected. On iOS 18.0 beta 3, the StateObject is initialized only once initially. However, if you swipe down to dismiss the DetailView, the StateObject is unexpectedly initialized again. Expected Behavior: The StateObject should be initialized only once, and should not be reinitialized when dismissing the DetailView. Please investigate this issue. FB14283951 import SwiftUI class Object: ObservableObject { @Published var flag = false init() { print("object init") } } struct DetailView: View { @StateObject var object = Object() var body: some View { Text("\(object.flag)") } } struct ContentView: View { @State var showingFirst = false @State var showingSecond = false var body: some View { NavigationStack { ZStack { Button("First") { showingFirst = true } .sheet(isPresented: $showingFirst) { NavigationStack { // replace this ZStack with Form, List, issue exists. // remove this ZStack, issue gone. ZStack { Button("Second") { showingSecond = true } .sheet(isPresented: $showingSecond) { DetailView() } } } // 2nd NavigationStack } // 1st sheet } // ZStack } // 1st NavigationStack } // body } // ContentView
1
0
150
1w
TextEditor Issue with Long Text Input
I'm encountering an issue with the TextEditor in my app when users input long texts. Specifically, when entering a large amount of text with many lines, not all of the text is visible. For example, after inputting the entire story of Cinderella, adding or deleting text causes the text towards the end to become obscured and not visible. A sample project illustrating this issue is available on GitHub: https://github.com/fuziki/TextEditorManyLinesIssue I have included a video in the project file demonstrating this issue. Is there a way to resolve this issue? Platform and Development Environment. iOS: iOS 17.5.1, Xcode 15.2 (15C500b)
2
0
163
1w
WatchOS 10.5 TabView Mem Leak Help Please
Target: WatchOS 10.5 NOTE: This is a watchOS only app Given: A single view containing NavigationSplitview, with the List in the "sidebar", a TabView in the "detail" and a TabView in a sheet attached to each tab in the "detail" view. When: Navigating between top-level list and "detail" TabView, or navigating through "detail" to "sheet" TabView Then: Memory leaks occur. If the TabView() views are replaced with List() views there are no longer memory leaks. There are no reference types involved. Everything is in Structs Code below causes the issue which can be observed in Instruments. So my question is what have I coded incorrectly to cause this issue? Or, How can I fix this? Thanks in advance. @main struct VerticalTabView_MemLeak: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { struct ParentItem: Identifiable, Hashable { var id = UUID() var name: String var children: [Item] init(_ name: String, _ children: [Item]){ self.name = name self.children = children } } struct Item: Identifiable, Hashable { var id: UUID = UUID() var name: String init(_ name: String){ self.name = name } } @State var selectedParentItem: ParentItem? @State var selectedItem: Item? var parentItems = [ ParentItem("A", [Item("one"),Item("two"),Item("three")]), ParentItem("B", [Item("four"),Item("five"),Item("six")]), ParentItem("C", [Item("seven"),Item("eight"),Item("nine")]) ] var body: some View { NavigationSplitView { List(selection: $selectedParentItem) { ForEach(parentItems, id: \.id) { parentItem in NavigationLink(value: parentItem) { HStack { Text(parentItem.name) } .padding() } } } .navigationTitle("Top Level") } detail: { if let items = selectedParentItem?.children { TabView(selection: $selectedItem) { ForEach(items, id:\.id) { item in Text(verbatim: item.name) .tag(item) .onTapGesture { selectedItem = item } } } .tabViewStyle(.verticalPage) .navigationTitle(selectedParentItem?.name ?? "") .sheet(item: $selectedItem, onDismiss: { selectedItem = nil }, content: { item in TabView { Text(item.name).foregroundStyle(.yellow) Text(item.name).foregroundStyle(.yellow) } .tabViewStyle(.verticalPage) .navigationTitle(selectedParentItem?.name ?? "") }) } } } } #Preview { ContentView() }
1
0
163
1w
Error when clicking on TextField : CLIENT ERROR: TUINSRemoteViewController does not override -viewServiceDidTerminateWithError: and thus cannot react to catastrophic errors beyond logging them
Hello, I face an error everytime I want to interact with a TextField. The XCode debug area is showing : CLIENT ERROR: TUINSRemoteViewController does not override -viewServiceDidTerminateWithError: and thus cannot react to catastrophic errors beyond logging them There is no crash, and the text field is working fine. I am developing for MacOS using a macbook pro Intel from 2019 with Sonoma 14.5 and Xcode 15.4 and I think that I noticed since the release of Sonoma. I was not particularly concerned by it but I noticed that interacting with the textField was leading to severe hang in my app, and micro-hang in the test app and I am wondering is these two issues could be related. The message is easy to reproduce. Just create a new Project/Application/App using SwiftUI and add a TextField to the ContentView. When you start app, click or double click on the text field, enter a message and press enter. import SwiftUI struct ContentView: View { @State var value: String = "" var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") TextField(text: $value, label: { Text("Test") } ) } .padding() } } Did you notice the same thing ? How I could solve it ? Note : I already posted the problem on Swift forums but it was close because related to SwiftUI https://forums.swift.org/t/error-when-clicking-on-textfield-client-error-tuinsremoteviewcontroller-does-not-override-viewservicedidterminatewitherror-and-thus-cannot-react-to-catastrophic-errors-beyond-logging-them/72134/1 Thank you
10
8
955
1w
Swift MultiDatePicker doesn't detect dates that have been saved previously and then loaded in from firebase.
Hey, currently working on my first SwiftUI app in college and would appreciate any help. I have an issue where when dates are loaded from firebase into the "selectedDates" array of my MultiDatePicker, the onChange function does not recognize dates that are already in the "selectedDates" array, instead re-adding them to the array. I.e. if I have loaded July 19th into the multidatePicker, it displays on the calendar, but clicking July 19th on the multidatepicker calendar view doesn't remove it from the "selectedDates" array. This is the code for the view: VStack { MultiDatePicker("Select dates", selection: $selectedDates) .padding() .onChange(of: selectedDates) { oldValue, newValue in saveDates(dates: selectedDates) } List(savedDates, id: \.self) { date in Text("\(date, formatter: dateFormatter)") } .listStyle(.plain) } .onAppear { loadSavedDates() } Where selectedDates is a state variable: @State var selectedDates: Set<DateComponents> = [] If nothing is on Firebase, the selection and deselection of dates happens fine, but if I am loading dates from firebase then the multidatepicker doesn't detect de-selection of dates. Here's my code for loading the dates from firebase: func loadSavedDates() { let db = Firestore.firestore() let uid = try! AuthenticationManager.shared.getAuthenticatedUser().uid print("User ID: \(uid)") print(widget.id.uuidString) db.collection("spaces") .document(spaceId) .collection("dates") .document(widget.id.uuidString)//widget.id.uuidString .getDocument {document, error in if let document = document { if let dateStrings = document.data()?[uid] as? [String] { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium self.savedDates = dateStrings.compactMap { dateFormatter.date(from: $0) }.sorted(). let calendar = Calendar.current self.selectedDates = Set(self.savedDates.map { calendar.dateComponents([.year, .month, .day], from: $0) }). for component in selectedDates { print(component.isValidDate) } } } else { print("Document does not exist") } } As you can see, I believe I am setting the selectedDates array correctly with datecomponents. Is there a problem with my code or is there just no way to pass dates from Firebase into multidatepicker?
0
0
172
1w
Infinite loop using NavigationStack
Hello. I've seen some other posts about NavigationStack, but my variation seems a little different. FYI, I have not migrated from ObservableObject to Observable yet. However, having a path in either seems to be a factor in this issue. My code has no issues when built with Xcode 15. When built with Xcode 16 I keep hitting scenarios where the .onAppear for my first tab gets called over and over again endlessly. If I go to my second tab, which uses a NavStack with a path and then navigate anywhere my .onAppear for my FIRST tab gets call endlessly. I’ll sometimes see a “double push” to the stack. (Someone posted a video of this happening on Mastodon, which apparently I’m not allowed to link to here.) The second tab is accessing the path property via an @EnvironmentObject. I can stop this endless loop by removing @Published from the property in my ObservableObject that holds my path. But then if I go to my third tab, which does NOT use a path, the .onAppear for my FIRST tab again gets called endlessly. So far on Mastodon I’ve seen three people encountering problems possibly related to storing a path in something being observed. Feedback requires a sample project, which I am having trouble creating to show the problem.
4
1
196
1w
Live Activity Text Style Issue in iOS Simulator's lock screen (iOS 17.2)
Environment: iOS Version: 17.2 iOS Simulator Version: 17.2 Xcode Version: 15.2 Device: iPhone 15 Pro Max App Target Version: iOS 17.2 Preconditions: App with Live Activity feature is installed. Device/Simulator is running iOS 17.2. Steps to Reproduce: Start the app and initiate a Live Activity with text styled as .timer. Lock the device screen or switch to the lock screen view in the iOS Simulator. Observe the Live Activity on the lock screen, noting the text style. Unlock the device. This time noting the .timer changed its style. The text style of the Live Activity remains consistent both on the lock screen and after unlocking the device, maintaining its .timer style throughout its lifecycle. Frequency: Occurs every time the steps are reproduced.
4
2
545
1w
SwiftUI design elements
Hello everyone, for a personal project I'd like to reproduce a design element from Apple's saving application. I'd like to display three rectangles containing text: two horizontally aligned and one next to it. And I'd like the height of the last rectangle to be equal to the height of the two smallest. Does anyone have a solution? Please provide a sample code
4
0
249
1w
How to resolve SwiftUI.DynamicProperty on MainActor compiler warning on 6.0?
Hi! I'm running into a warning from a SwiftUI.DynamicProperty on a 6.0 development build (swift-6.0-DEVELOPMENT-SNAPSHOT-2024-03-26-a). I am attempting to build a type (conforming to DynamicProperty) that should also be MainActor. This type with also need a custom update function. Here is a simple custom wrapper (handwaving over the orthogonal missing pieces) that shows the warning: import SwiftUI @MainActor struct MainProperty: DynamicProperty { // Main actor-isolated instance method 'update()' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode @MainActor func update() { } } Is there anything I can do about that warning? Does the warning correctly imply that this will be a legit compiler error when 6.0 ships? I can find (at least) two examples of types adopting DynamicProperty from Apple that are also MainActor: FetchRequest and SectionedFetchRequest. What is confusing is that both FetchRequest^1 and SectionedFetchRequest^2 explicitly declare their update method to be MainActor. Is there anything missing from my Wrapper declaration that can get me what I'm looking for? Any more advice about that? Thanks!
3
0
456
1w
SwiftUI Map Annotation Coordinate Animation
Hi, I have a SwiftUI Map with a set of three annotations. These annotations move around, and I would like to animate their movement from one coordinate to another, but I'm not finding a way to do that. I've tried using withAnimation { } when setting my array of Identifiable models that back the Annotations, and I've tried adding the .animation(.default, annotationModels) modifier to my Map object (where annotationModels is the array that backs my Annotations). The animation modifier doesn't work on Annotation structs, and it doesn't work if I add the animation modifier within the Annotation's view either. Does anyone have any suggestions on how I might be able to animate the coordinates of annotations using a SwiftUI Map? Does the problem have to do with the fact that I have an array of these annotations?
0
0
149
1w
Text Don't Show in swipeActions buttons !
Hi, I have the below code and don't know why the text doesn't show fro swipe buttons just the icons show ? Kind Regards import SwiftUI struct NewView: View { var body: some View { NavigationStack { List { ForEach(1...7, id: \.self) { number in VStack { Text("Item \(number)") .padding() } .swipeActions(edge: .trailing) { Button(role: .destructive) { withAnimation { deletePatient2() } } label: { Label("Delete", systemImage: "trash.fill") } Button { deletePatient2() // toDoToEdit = item } label: { Label("Edit", systemImage: "pencil") } .tint(.orange) } } } } .listStyle(.plain) } func deletePatient2() { } } #Preview { NewView() }
3
0
161
1w
Swift Chart Zoom/Magnification/Pinch Gesture
Is there any approach or sample code available to use these APIs: .chartScrollableAxes(.horizontal) .chartScrollPosition(x: ...) .chartScrollPosition(initialX: ...) .chartScrollTargetBehavior(...) .chartXVisibleDomain(length: ...) Plus a gesture recognised or Pinch or Magnification to create a Swift Chart with an X axis that can be zoomed in or out with a pinch gesture? And when zoomed in at any level above 0, the chart can then be scrolled left to right along the X axis. I've had success using .chartScrollableAxes with .chartXSelection in parallel, so would also like to keep the ability to select X values too.
0
0
164
1w
Can't figure out why Toolbar is not conforming to view
ToolbarItem in group is not conforming to view for some reason, here's my code: var body: some View { NavigationStack { Form { TextField("Company Name", text: $companyName) TextField("Role", text: $role) TextField("Location", text: $location) TextField("Yearly Salary", value: $yearlySalary, format: .currency(code: "USD")) .keyboardType(.decimalPad) } .navigationTitle("Add Application") .navigationBarTitleDisplayMode(.large) .toolbar { ToolbarItem(placement: .navigationBarLeading) { Button("back") { dismiss() } } ToolbarItem(placement: .navigationBarTrailing) { Button("Save") { let appdata = ApplicationData( companyName: companyName, role: role, location: location, yearlySalary: yearlySalary, dateApplied: dateApplied, notes: notes) // Save the application data dismiss() } } } } } The error reads: Static method 'buildExpression' requires that 'ToolbarItem<(), Button>' conform to 'View' I'm trying to change it up but I can't get past this error for some reason
2
0
158
1w