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

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI: .textSelection(.enabled) not working in List on iOS 18
In iOS 18, textSelection(_:) not working in List. So, I can't copy text. Works on iOS 17 and earlier. Is this a bug and is there any solution? // Not Work: iOS 18 struct ContentView: View { var body: some View { List { Text("Hello World") .textSelection(.enabled) } } } // Work: iOS 18 and earlier struct ContentView: View { var body: some View { Text("Hello World") .textSelection(.enabled) } }
3
3
376
Sep ’24
Considering Alternatives to SwiftUI for a Complex App
I am working on an application that has some complex navigation needs, and I'm considering abandoning SwiftUI, at least in a few core areas of the app. I found SwiftUI intuitive and useful for simple things like: Using a state to toggle the appearance or disappearance of an element Using state to alter the look of UI elements Watching the values of built-in interfaces like TextField or Slider Controlling out-of-the-box UI elements like NavigationSplitView But now I've got a UI that depends on a data model that can change at any time, and from that data I'll display lists of objects, and objects in detail, and all of this will be displayed according to a NavigationPath that depends on the data model's internal structure. This means that, for instance, I may be in the detail view of element X after having traveled to it from the detail view of element Y which was tapped in a list of XYZ, which was the result of tapping into part of the detail view of element W. This whole path could be invalidated by an update to the data model when it's received from the network. Furthermore, any element could have it's details changed, or be deleted, and I'd want the UI to reflect that right away if possible. For the navigation work, I'm still optimistic that custom edits to a NavigationPath could be the way to go. However, for propagating data updates around my app, I know @State, @Bindable, etc are intended to handle this kind of thing, but when I'm try to send these bindings through the circuitous path of views I mentioned above, and I run into any unexpected hiccup, it feels like I'm at a disadvantage when debugging because I'm relying on opaque SwiftUI Magic to handle things under the hood in a way I don't really understand. I could put more effort into learning how this works, and potentially come up against some platform limitations, bugs, or other dead-ends, or I could just use Pub/Sub and a network of custom queues/pipes, and send updates around my app the old fashioned way, but using primitives whose functions are clear to me. I've been using SwiftUI for about a year and it still trips me up, and I have watched a few WWDC talks on the topic. I'd appreciate any advice on this front from the frequenters of this forum. Thanks for reading my post.
3
0
284
Oct ’24
Using truncationMode
Hi, The example that Apple shows in link below doesn't show how truncationMode works, because the text get truncated anyway when its length it more than frame height so what's the use of truncationMode ? https://developer.apple.com/documentation/swiftui/view/truncationmode(_:) -- Kind Regards
1
0
156
Sep ’24
Buttons in NavigationBar
Hi Guys, I saw in iOS 18 (Photos App) that there are buttons (in an scrollview) below the navigation title and inside the navigation bar. Is there an new API or an method to "clone" this UI without using: .safeAreaInset(edge: .top, content: { }) Thanks in advance for any feedback and help!
0
0
221
Sep ’24
Getting different StoreKit results between SandBox and StoreKitTransactions in Xcode
I’m using ‘Offer Codes’ in App Store Connect for subscriptions. I’m also using a StoreKit implementation that uses the subscriptionStatusTask modifier to assess if the user is subscribed or not. The part I’m not sure of is whether or not the subscriptionStatusTask modifier will recognize the status if the user has used an offer code. I think it should, as that modifier checks for currentEntitlements, and returns appropriately. I’ve been trying to test this out with the StoreKitTransactions system in Xcode, as SandBox does not currently support this. From what I can tell, this way does in fact seem to allow the user to access the app with an offer code. The app does not present the StoreKit view. However, when I’ve tried this with an actual user on the app store (aren’t mom’s great?), the offer code does not take, and they are presented with that StoreKit view. Not great. So can someone please shed some light on this? Is my understanding correct here? What else do I need to do?
0
0
241
Sep ’24
Request .full contacts authorization after being granted .limited
We're adjusting to the new iOS 18 .limited contacts access mode. In our app, we don't request contacts right away. We have a search bar where users can search through their own contacts and select one using the ContactAccessButton. If they do select one, then they're prompted to "Grant Limited Access", not "Grant Full Access", as the screenshot shows below. Later on, we want to offer the ability for users to sync their entire contact book with our app. This will improve their experience on the app by automatically finding all their friends already on the app, without them having to do the manual work of clicking on every single contact in the ContactsAccessPicker. Is this possible right now? It doesn't seem like it—when I call ContactsStore.requestAccess(for: .contacts) while in .limited access mode, nothing happens. But I would like to show a prompt that gives the user the ability to grant all their contacts to improve their experience.
1
0
262
Sep ’24
Xcode 16 SwiftUI List Fast Scrolling Issue
Hi! When building my app using Xcode 16, fast scrolling (using scrollViewProxy.scrollTo) a list would result in items not appearing even when scrolling stopped. This does not happen when the app is built with Xcode 15, even on iOS 18. I'm also getting this error in the logs: List failed to visit cell content, returning an empty cell. - SwiftUICore/Logging.swift:84 - please file a bug report.
2
2
431
Sep ’24
How do you let SwiftUI View know that ViewModel's computed property has changed?
Imagine you have ViewModel which computed property may change from time to time: import Foundation class ViewModel: ObservableObject { private var val = 42; var compProp: Int { return val } func maybeChange() { if (Int.random(in: 0..<2) == 1) { val += 1 ??? //heyViewThePropertyIsChanged(nameof(compProp)) } } } How could you force the View: import SwiftUI struct ContentView: View { @StateObject var viewModel: ViewModel var body: some View { VStack { Text("\(viewModel.compProp)").font(.title) } .frame(minWidth: 320) .toolbar { Button(action: viewModel.maybeChange) { Label("Maybe", systemImage: "gear.badge.questionmark") } }.padding() } } to reflect such a change?
3
0
196
Sep ’24
Swift Charts - weak scrolling performance
Hello there! I wanted to give a native scrolling mechanism for the Swift Charts Graph a try and experiment a bit if the scenario that we try to achieve might be possible, but it seems that the Swift Charts scrolling performance is very poor. The graph was created as follows: X-axis is created based on a date range, Y-axis is created based on an integer values between moreless 0-320 value. the graph is scrollable horizontally only (x-axis), The time range (x-axis) for the scrolling content was set to one year from now date (so the user can scroll one year into the past as a minimum visible date (.chartXScale). The X-axis shows 3 hours of data per screen width (.chartXVisibleDomain). The data points for the graph are generated once when screen is about to appear so that the Charts engine can use it (no lazy loading implemented yet). The line data points (LineMark views) consist of 2880 data points distributed every 5 minutes which simulates - two days of continuous data stream that we want to present. The rest of the graph displays no data at all. The performance result: The graph on the initial loading phase is frozen for about 10-15 seconds until the data appears on the graph. Scrolling is very laggy - the CPU usage is 100% and is unacceptable for the end users. If we show no data at all on the graph (so no LineMark views are created at all) - the result is similar - the empty graph scrolling is also very laggy. Below I am sharing a test code: @main struct ChartsTestApp: App { var body: some Scene { WindowGroup { ContentView() Spacer() } } } struct LineDataPoint: Identifiable, Equatable { var id: Int let date: Date let value: Int } actor TestData { func generate(startDate: Date) async -> [LineDataPoint] { var values: [LineDataPoint] = [] for i in 0..<(1440 * 2) { values.append( LineDataPoint( id: i, date: startDate.addingTimeInterval( TimeInterval(60 * 5 * i) // Every 5 minutes ), value: Int.random(in: 1...100) ) ) } return values } } struct ContentView: View { var startDate: Date { return endDate.addingTimeInterval(-3600*24*30*12) // one year into the past from now } let endDate = Date() @State var dataPoints: [LineDataPoint] = [] var body: some View { Chart { ForEach(dataPoints) { item in LineMark( x: .value("Date", item.date), y: .value("Value", item.value), series: .value("Series", "Test") ) } } .frame(height: 200) .chartScrollableAxes(.horizontal) .chartYAxis(.hidden) .chartXScale(domain: startDate...endDate) // one year possibility to scroll back .chartXVisibleDomain(length: 3600 * 3) // 3 hours visible on screen .onAppear { Task { dataPoints = await TestData().generate(startDate: startDate) } } } } I would be grateful for any insights or suggestions on how to improve it or if it's planned to be improved in the future. Currently, I use UIKit CollectionView where we split the graph into smaller chunks of the graph and we present the SwiftUI Chart content in the cells, so we use the scrolling offered there. I wonder if it's possible to use native SwiftUI for such a scenario so that later on we could also implement some kind of lazy loading of the data as the user scrolls into the past.
1
1
278
3w
[NetworkComponent] Cannot find component's entity (guid=***, typeID=***, type=CustomComponentRCPInputTargetComponent, entity=xxxx).
Hi. I recently added SwiftUI context menus and picker menus to my app, but when they are activated they flicker rapidly, and it is impossible to select anything (there is no hover effect either). When these menus are activated, the console prints lots of warning messages similar to this: [NetworkComponent] Cannot find component's entity (guid=14395713952467043328, typeID=295756909031380028, type=CustomComponentRCPInputTargetComponent, entity=0x1047c6750). This issue doesn't seem to happen on visionOS 1.2 simulator, but is reliably reproducible on visionOS 2.0 simulator and device. Any idea what this might be related to? I am attempting to narrow down on the issue but it's challenging to do so without knowing what the error is about. Thanks!
1
0
311
Sep ’24
Issue with Keyboard Avoidance for Sheet View in SwiftUI
I am currently working on a comments section modeled after TikTok's/Instagram's comment sections for a media app. The view is a sheet view that is presented as follows: .sheet(isPresented: $showChat) { TakesChatView(viewModel: viewModel) .presentationDetents([.medium, .large]) .presentationDragIndicator(.hidden) .overlay( VStack { RoundedRectangle(cornerRadius: 2) .fill(Color.gray) .frame(width: 40, height: 5) .padding(.top, 15) .opacity(0.8) Label("Chat", systemImage: "message.badge") .lineLimit(nil) .padding(.top, 5) .padding([.leading, .trailing], 16) Divider() .padding(.top, 5) .padding([.leading, .trailing], 16) Spacer() } .frame(maxWidth: .infinity, alignment: .top) ) }.ignoresSafeArea(.keyboard, edges: .bottom) However, some issues arise regarding keyboard avoidance. Currently, when the user taps on the TextField to type a comment, the keyboard shifts the entire view upwards as it pops up. Instead, I need it where I can still view the comments without the keyboard affecting their placement when it pop up. Below is the associated code for the comment view: struct TakesChatView: View { @ObservedObject var viewModel: TakeCommentViewModel @FocusState var focus: Bool @State private var selectedMedia: [PhotosPickerItem] = [] @State private var selectedImageData: [Data] = [] @State private var selectedGIFData: [Data] = [] @State private var selectedVideoData: [Data] = [] var textFieldNotEmpty: Bool { !viewModel.textToPost.isEmpty || !selectedImageData.isEmpty || !selectedGIFData.isEmpty || !selectedVideoData.isEmpty } var body: some View { GeometryReader { _ in ZStack { VStack { contentView commentTextField .padding(.top,5) } } } .ignoresSafeArea(.keyboard, edges: .bottom) .background(Color.containerBackground) .onChange(of: viewModel.focus) { focus in self.focus = focus } .onChange(of: selectedMedia) { _ in loadMedia() } } var contentView: some View { VStack { Spacer().frame(height: 105) ScrollViewReader { scroll in ScrollView(showsIndicators: true) { ForEach(viewModel.comments, id: \.self) { comment in TakeCommentView( comment: comment, viewModel: self.viewModel ) .padding(.horizontal, 10) .id(comment.documentID) } .onChange(of: viewModel.commentAdded) { id in scroll.scrollTo(id, anchor: .bottom) viewModel.commentAdded = nil } } .scrollDismissesKeyboard(.immediately) } } } } extension TakesChatView { var commentTextField: some View { VStack { mediaPreview HStack { TextField("Type your comment", text: $viewModel.textToPost, axis: .vertical) .keyboardType(.twitter) .padding([.leading, .vertical], 6) .focused($focus) PhotosPicker(selection: $selectedMedia, matching: .any(of: [.images, .videos]), photoLibrary: .shared()) { ComposeType.media.image .frame(width: 40, height: 40, alignment: .center) } .onAppear { selectedMedia.removeAll() selectedImageData.removeAll() selectedGIFData.removeAll() selectedVideoData.removeAll() } postButton } .border(.lightGray, width: 1, cornerRadius: 10) .padding([.bottom, .horizontal], 10) } } } I have tried using .ignoresSafeAres(), .safeAreaInset(), and custom keyboard observer functions but to no avail. How do I fix this issue?
0
0
223
Sep ’24
Text Max Character Number SwiftUI
Hi, Some times long text damage the design of views it might go to a second row and increase view height and damage the overall design, so how to solve this issue, is there a way to set a Max Characters number for Text and TextField views in SwiftUI ? and maybe show few dots as used in some designs ? Kind Regards
1
0
253
Sep ’24
Xcode cloud unable to run tests;
Error: 'Runningboard has returned error 5' I am able to run my unit tests locally just fine. When I run them to from xcode cloud It fails everytime. I did notice in app store connect that it gives me a warning 'Grant access to the following repositories to allow them to be used for this product.' as I am using google sign in iOS(https://github.com/google/googlesignin-ios.git). However I cannot grant this access as I do not have privileges to google code base. I have imported the google sign in via swift package manager and everything works fine. This is the report from xcode cloud if it helps. Happy to add any additional info that will help
2
0
348
3w
Adapt distance/depth of view relative to user
Hi, I'm currently working on some messages that should appear in front of the user depending on the system's state of my visionOS app. How am I able to change the distance of the appearing message relative to the user if the message is displayed as a View. Or is this only possible if I would create an enitity for that message, and then set apply .setPosition() and .relativeTo() e.g. the head anchor? Currently I can change the x and y coordinates of the view as it works within a 2D space, but as I'm intending to display that view in my immersive space, it would be cool if I can display my message a little bit further away in the user's UI, as it currently is a little bit to close in the user's view. If there is a solution without the use of entities I would prefer that one. Thank you for your help! Below an example: Feedback.swift import SwiftUI struct Feedback: View { let message: String var body: some View { VStack { Text(message) } } .position(x: 0, y: -850) // how to adapt distance/depth relative to user in UI? } } ImmersiveView.swift import SwiftUI import RealityKit struct ImmersiveView: View { @State private var feedbackMessage = "Hello World" public var body: some View { VStack {} .overlay( Feedback(message: feedbackMessage) ) RealityView { content in let configuration = SpatialTrackingSession.Configuration(tracking: [.hand]) let spatialTrackingSession = SpatialTrackingSession.init() _ = await spatialTrackingSession.run(configuration) // Head let headEntity = AnchorEntity(.head) content.add(headEntity) } } }
2
0
310
Sep ’24
Crash on launch from all TestFlight builds, but when loading the app from Xcode
We are preparing a launch for iOS 18, and we experienced crashes from iOS 17 devices. If I load the app right from Xcode 16 RC to the iOS 17 device, then it works fine, but if I download it from TestFlight, the nit crashes. The app crashes immediately upon launch due to a missing symbol in the Foundation framework. I'm hoping someone can provide insights or suggestions on how to resolve this. Error Message CopySymbol not found: _$s10Foundation14NSDecimalRoundyySpySo0B0aG_SPyADGSiSo14NSRoundingModeVtF Referenced from: <C1ABDA48-29EE-3674-8554-669220A76F81> /Volumes/VOLUME/*/CamPlan.app/CamPlan Expected in: <D92E19C1-6299-3E94-8614-C505D5ABCCDB> /System/Library/Frameworks/Foundation.framework/Foundation What I've Tried Verified that the app is compiled with the latest Xcode version Checked for any usage of private APIs (none found) Reviewed usage of Foundation framework methods, especially those related to NSDecimalRound Questions What could be causing this symbol to be missing? Are there any known issues with NSDecimalRound or related functions in recent iOS versions? How can I identify which part of my code is trying to use this missing symbol?
6
1
803
Sep ’24
Tab button's ax identifier is missing when using `.sidebarAdaptable` TabViewStyle
Hello, I found that if you apply the new .sidebarAdaptable tab view style, the accessibility identifiers of tab bar buttons are missing. import SwiftUI struct ContentView: View { var body: some View { TabView { Tab("Received", systemImage: "tray.and.arrow.down.fill") { Text("Received") } .accessibilityIdentifier("tab.received") // 👀 Tab("Sent", systemImage: "tray.and.arrow.up.fill") { Text("Sent") } .accessibilityIdentifier("tab.sent") // 👀 Tab("Account", systemImage: "person.crop.circle.fill") { Text("Account") } .accessibilityIdentifier("tab.account") // 👀 } .tabViewStyle(.sidebarAdaptable) // 👈 if remove this, ax identifiers are ok } } #Preview { ContentView() } The identifiers automatically appear after a few seconds. But this behaviour breaks a lot of the UI test cases.
2
0
224
Sep ’24
LongPressGesture does not work as expected in Xcode Version 16.0 (16A242) and iOS 18
When I copy and paste example code in apple developer documentation, LongPressGesture does not work as expected in Xcode Version 16.0 (16A242) and iOS 18. It seems updating(_:body:) method does not work when used with LongPressGesture. When I make a breakpoint in updating(_:body:) method and long press the blue circle on the screen of simulator(or device), it is expected to be caught in breakpoint or it is expected that color of circle turns from blue to red to green. However, it is not caught in breakpoint and never turns to red. Question of Stackoverflow is about same issue and I can not use onLongPressGesture method to implement required feature of my app. Development environment: Xcode Version 16.0 (16A242), macOS 14.5 Run-time configuration: iOS 18.0
10
8
592
Sep ’24