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

SwiftUI Documentation

Posts under SwiftUI subtopic

Post

Replies

Boosts

Views

Activity

SwiftUI TextField corrupts selection when inserting utf16
The example code below shows what I am trying to achieve: When the user types a '*', it should be replaced with a '×'. It looks like it works, but the cursor position is corrupted, even though it looks OK, and the diagnostics that is printed below shows a valid index. If you type "12*34" you get "12×43" because the cursor is inserting before the shown cursor instead of after. How can I fix this? struct ContentView: View { @State private var input: String = "" @State private var selection: TextSelection? = nil var body: some View { VStack { TextField("Type 12*34", text: $input, selection: $selection) .onKeyPress(action: {keyPress in handleKeyPress(keyPress) }) Text("Selection: \(selectionAsString())") }.padding() } func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result { if (keyPress.key.character == "*") { insertAtCursor(text: "×") moveCursor(offset: 1) return KeyPress.Result.handled } return KeyPress.Result.ignored } func moveCursor(offset: Int) { guard let selection else { return } if case let .selection(range) = selection.indices { print("Moving cursor from \(range.lowerBound)") let newIndex = input.index(range.lowerBound, offsetBy: offset, limitedBy: input.endIndex)! let newSelection : TextSelection.Indices = .selection(newIndex..<newIndex) if case let .selection(range) = newSelection { print("Moved to \(range.lowerBound)") } self.selection!.indices = newSelection } } func insertAtCursor(text: String) { guard let selection else { return } if case let .selection(range) = selection.indices { input.insert(contentsOf: text, at: range.lowerBound) } } func selectionAsString() -> String { guard let selection else { return "None" } switch selection.indices { case .selection(let range): if (range.lowerBound == range.upperBound) { return ("No selection, cursor at \(range.lowerBound)") } let lower = range.lowerBound.utf16Offset(in: input) let upper = range.upperBound.utf16Offset(in: input) return "\(lower) - \(upper)" case .multiSelection(let rangeSet): return "Multi selection \(rangeSet)" @unknown default: fatalError("Unknown selection") } } }
Topic: UI Frameworks SubTopic: SwiftUI
6
0
66
May ’25
Application crashes when using TextEditor(text, selection)
I have a TextEditor, to the constructor of which in addition to the text I pass an object of the TextSelection? type. I check on the Simulator with iOS 18.2. An attempt to clear the text leads to a crash with the message "Thread 1: Fatal error: String index is out of bounds" in Xcode. More about the error: libswiftCore.dylib`_swift_runtime_on_report: -> 0x194f32024 <+0>: ret More about the reproduction conditions: struct MyView: View { @Bindable private var viewModel = MyViewModel() @State var myTextSelection: TextSelection? = nil var body: some View { ZStack { // Some other code myEditor // Some other code } .toolbar { ToolbarItem(placement: .primaryAction) { Button { viewModel.clear() } label: { Label("Clear", systemImage: "eraser") } } } } var myEditor: some View { ZStack(alignment: .topLeading) { TextEditor(text: $viewModel.text, selection: $myTextSelection) .disableAutocorrection(true) .autocapitalization(.sentences) } // Some other code } } MyViewModel: @Observable final class MyViewModel: ObservableObject { var text: String = "" func clear() { text = "" } }
1
0
66
May ’25
Can You Debug a Widget on Actual Device?
I'm working on an iOS app with a Widget. I am able to display the Widget on the iPhone 16 Pro Simulator. It doesn't appear on iPad mini 6th gen., though. Anyway, I want to make sure that it works on an actual device. If I try to add the Widget to the Home Screen, I cannot find it in the search list on iPhone XR and iPad 9th gen. If I set the target to that of the widget, Xcode gives me the following error. SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget 'some bundle ID' error: … I hope that's not a sign of trouble. So how do you debug a Widget on an Actual Device? I've read some topics like this one here. Thanks.
2
0
56
May ’25
How to effectively use task(id:) when multiple properties are involved?
While adopting SwiftUI (and Swift Concurrency) into a macOS/AppKit application, I'm making extensive use of the .task(id:) view modifier. In general, this is working better than expected however I'm curious if there are design patterns I can better leverage when the number of properties that need to be "monitored" grows. Consider the following pseudo-view whereby I want to call updateFilters whenever one of three separate strings is changed. struct FiltersView: View { @State var argument1: String @State var argument2: String @State var argument3: String var body: some View { TextField($argument1) TextField($argument2) TextField($argument3) }.task(id: argument1) { await updateFilters() }.task(id: argument2) { await updateFilters() }.task(id: argument3) { await updateFilters() } } Is there a better way to handle this? The best I've come up with is to nest the properties inside struct. While that works, I now find myself creating these "dummy types" in a bunch of views whenever two or more properties need to trigger an update. ex: struct FiltersView: View { struct Components: Equatable { var argument1: String var argument2: String var argument3: String } @State var components: Components var body: some View { // TextField's with bindings to $components... }.task(id: components) { await updateFilters() } } Curious if there are any cleaner ways to accomplish this because this gets a bit annoying over a lot of views and gets cumbersome when some values are passed down to child views. It also adds an entire layer of indirection who's only purpose is to trigger task(id:).
2
0
59
May ’25
onDrop() modifier with multiple UTTypes giving the least helpful one?
Hey folks I'm trying to use .onDrop() on a view that needs to accept files. This works fine, I specify a supportedContentTypes of [.fileURL] and it works great. I got a request to add support for dragging the macOS screenshot previews into my app and when I looked at it, they aren't available as a URL, only an image, so I changed my array to [.fileURL, .image]. As soon as I did that, I noticed that dragging any image file, even from Finder, calls my onDrop() closure with an NSItemProvider that only knows how to give me an image, with no suggestedName. Am I missing something here? I had been under the impression that: The order of my supportedContentTypes indicates which types I prefer (although I now can't find this documented anywhere) Where an item could potentially vend multiple UTTypes, the resulting NSItemProvider would offer up the union of types that both it, and I, support. If it helps, I put together a little test app which lets you select which UTTypes are in supportedContentTypes and then when a file is dragged onto it, it'll tell you which content types are available - as far as I can tell, it's only ever one, and macOS strongly prefers to send me an image vs a URL. Is there anything I can do to convince it otherwise?
4
0
107
May ’25
NWPathMonitor Failing
I need to check the network connection with NWPathMonitor. import Foundation import Network class NetworkViewModel: ObservableObject { let monitor = NWPathMonitor() let queue = DispatchQueue(label: "NetworkViewModel") @Published var isConnected = false var connectionDescription: String { if isConnected { return "You are connected." } else { return "You are NOT connected." } } init() { monitor.pathUpdateHandler = { path in DispatchQueue.main.async { self.isConnected = path.status == .satisfied } } monitor.start(queue: queue) } } import SwiftUI struct ContentView: View { @StateObject private var networkViewModel = NetworkViewModel() var body: some View { VStack { } .onAppear { if networkViewModel.isConnected { print("You are connected.") } else { print("You are NOT connected.") } } } } So there is nothing special, not at all. Yet, if I test it with a totally new Xcode project for iOS, it fails and return !isConnected. I've tested it with a macOS application. And it fails. I've tested it with an actual device. It fails. I've tested it with an old project. It still does work. I have no mere idea why new Xcode projects all fail to detect the WiFi connection. This is a total nightmare. Does anybody have a clue? thanks.
7
0
120
May ’25
How to hide the tab bar in SwiftUI's TabView for macOS?
In SwiftUI for macOS, how can I hide the tab bar when using TabView? I would like to provide my own tab bar implementation. In AppKit's NSTabViewController, we can do the following: let tabViewController = NSTabViewController() tabViewController.tabStyle = .unspecified I've come across various posts that suggest using the .toolbar modifier, but none appear to work on macOS (or at least I haven't found the right implementation). struct ContentView: View { var body: some View { TabView { // ... content } <- which view modifier hides the tab bar? } } Latest macOS, Latest Xcode
3
0
94
May ’25
Reset SwiftUI animation for another step.
I was trying to move from appkit to swiftUI. As a learning project I am building a cellular automata style project based on Pattersons Worms.. I am trying something similar to the EA game Worms? for the Commodore 64. There is a video on YouTube of the game running, but I'm not allowed to link it here. The problem I have is that the animation is driven by a ruleset. When the automata hits a configuration that is not in the ruleset it is supposed to stop and ask the user. For each step the model returns either the next move, or nil to indicate the user need to make a choice that will be sent back to the model to be added to the ruleset. My current approach, and I might be following the wrong path, is a ZStack where the bottom level is the grid, the middle level is the established worm segments and the top level is either the animation of the next worm segment or the user chooser to choose the segment. I've only implemented the animation of the next worm segment. The idea is that when the model adds a segment that it first animated at the top level and then displayed by the middle level. Then the top level animates the next segment. I was animating the trim on the segment to draw the line. If the current move is nil, then the middle level draws the segment. If current move has a value, the animation draw it, and then on completion sets the current move to nil so that the bottom level draw it. The problem I ran into was resetting the animation to draw the next segment. I've tried two approaches. in one the completion resets the animation boolean variable, but I need a manual step to set the next stage of the animation. The other uses the completion to set the next step, but it the animation doesn't run for the step and the display is an always a step behind. I'm not sure how to both update the move and reset the animation at the same time. I have uploaded a simplified version without the full grid and simplified model to GitHub (https://github.com/thomasrdean/AnimationTest). Is there any other way to reset the animation the than the completion so I can use the completion to retrieve the next step from the model?
1
0
56
May ’25
Xcode 16.3(16E140) failing to debug run but succeeding to build.
Reproduction procedure Launch Xcode and press shift+command+N to create a macOS App project. Edit the generated ContentView.swift to the following content: struct ContentView: View { @State var txt: String = “” var body: some View { VStack { Text(“Hello, world!\(txt)”) TextField(“input”, text: $txt) onSubmit { // lack of a period letter. // .onSubmit { // Correct code print(“onSubmit\(txt)”) } } } } Build with command+B and it succeeds. Debug with command+R, but a rainbow wheel appears and the window does not show. An error is displayed in Xcode’s Preview Canvas, preventing preview.
1
0
44
May ’25
WidgetKit with Data from CoreData
I have a SwiftUI app. It fetches records through CoreData. And I want to show some records on a widget. I understand that I need to use AppGroup to share data between an app and its associated widget. import Foundation import CoreData import CloudKit class DataManager { static let instance = DataManager() let container: NSPersistentContainer let context: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "DataMama") container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group identifier)!.appendingPathComponent("Trash.sqlite"))] container.loadPersistentStores(completionHandler: { (description, error) in if let error = error as NSError? { print("Unresolved error \(error), \(error.userInfo)") } }) context = container.viewContext context.automaticallyMergesChangesFromParent = true context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) } func save() { do { try container.viewContext.save() print("Saved successfully") } catch { print("Error in saving data: \(error.localizedDescription)") } } } // ViewModel // import Foundation import CoreData import WidgetKit class ViewModel: ObservableObject { let manager = DataManager() @Published var records: [Little] = [] init() { fetchRecords() } func fetchRecords() { let request = NSFetchRequest<Little>(entityName: "Little") do { records = try manager.context.fetch(request) records.sort { lhs, rhs in lhs.trashDate! < rhs.trashDate! } } catch { print("Fetch error for DataManager: \(error.localizedDescription)") } WidgetCenter.shared.reloadAllTimelines() } } So I have a view model that fetches data for the app as shown above. Now, my question is how should my widget get data from CoreData? Should the widget get data from CoreData through DataManager? I have read some questions here and also read some articles around the world. This article ( https://dev.classmethod.jp/articles/widget-coredate-introduction/ ) suggests that you let the Widget struct access CoreData through DataManager. If that's a correct fashion, how should the getTimeline function in the TimelineProvider struct get data? This question also suggests the same. Thank you for your reading my question.
6
0
124
May ’25
Can SwiftUI TextFields in a List on macOS be marked as always editable?
In SwiftUI's List, on macOS, if I embed a TextField then the text field is presented as non-editable. If the user clicks on the text and waits a short period of time, the text field will become editable. I'm aware this is generally the correct behaviour for macOS. However, is there a way in SwiftUI to supress this behaviour such that the TextField is always presented as being editable? I want a scrollable, List of editable text fields, much like how a Form is presented. The reason I'm not using a Form is because I want List's support for reordering by drag-and-drop (.onMove). Use Case A view that allows a user to compose a questionnaire. They are able to add and remove questions (rows) and each question is editable. They require drag-and-drop support so that they can reorder the questions.
0
0
78
May ’25
Cannot configure contentShape for final preview of .contextMenu(menuItems: , preview: )
Without using a custom preview, you can set .contentShape(RoundedRectangle(cornerRadius: 30)) so that in the "zoomed in" preview of the contextMenu you can have a custom cornerRadius. However, this does not work if you create a custom preview, because then the ContentShape gets applied only to the LIFT PREVIEW, and not to the FINAL PREVIEW state. Heres a sample code - I'd love some support! :) import SwiftUI struct ContentView: View { var body: some View { VStack { Rectangle() .fill(Color.blue) .frame(width: 300, height: 300) .cornerRadius(30) .contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30)) .contextMenu { Button("Hello") {} Button("Goofy") {} } preview: { Rectangle() .fill(Color.blue) .frame(width: 300, height: 300) .cornerRadius(30) //.contentShape(RoundedRectangle(cornerRadius: 30)) //.contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30)) } Text("contextMenu item with large cornerRadius is not working as expected... No way to set contentShape to custom corner radius for final preview - not the lift preview") } } }
1
0
59
May ’25
Using .searchable inside NavigationStack inside TabView (iOS)
I noticed that when using .searchable inside a NavigationStack thats inside a TabView, the searchbar briefly overlays the content before disappearing. After that, it is hidden and appears as expected when swiping down. This only happens when the .searchable is inside the NavigationStack, there is at least one navigationTitle and the NavigationStack is inside a TabView. Tested on simulator and real device. I would appreciate any help. Thanks! struct FirstScreen: View { var body: some View { TabView { Tab("Tab", systemImage: "heart") { NavigationStack { NavigationLink { SecondScreen() } label: { Text("Go to second screen") } .navigationTitle("First Screen") } } } } } struct SecondScreen: View { @State private var text: String = "" var body: some View { List { Text("Some view that extends all the way to the top") } .searchable(text: $text) .navigationTitle("Second Screen") } }
2
0
71
May ’25
.highPriorityGesture Prevents Button Tap on iOS 17 and Earlier
In iOS 18, using .highPriorityGesture does not interfere with Button tap detection. However, on iOS 17 and earlier, setting a .highPriorityGesture causes the Button's tap action to stop responding. I am using .highPriorityGesture in an attempt to support both tap and long-press gestures on a Button, which works as expected in iOS 18. However, the same implementation prevents taps on earlier versions. Is using .highPriorityGesture on a Button not recommended in this case? Or is this an issue specific to how .highPriorityGesture behaves on iOS 17 and earlier? Below is a sample code: struct SampleButton: View { let title: String let action: () -> Void var body: some View { Button { NSLog("Tapped") action() } label: { Text(title) }.highPriorityGesture(LongPressGesture(minimumDuration: 0.5).onEnded { _ in NSLog("Long press.") action() }) } } struct ContentView: View { var body: some View { VStack { SampleButton(title: "Tap or LongPress") {} } } } Environment: Xcode: Version 16.3 (16E140) iOS: iOS 18.4(simulator), iOS 17.5, iOS 16.4, iOS 15.2
3
0
70
May ’25
Open new document in SwiftUI on iOS
I have a SwiftUI document based app. The iOS version has a Scene Delegate: class SceneDelegate: NSObject, UIWindowSceneDelegate { func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { for context in URLContexts { let url = context.url // url.scheme = my custom scheme let text = ... extracted from url ... // I want to open a new untitled document with text // but 'newDocument' has been explicitly marked unavailable for iOS } } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
42
May ’25
NewDocumentButton in DocumentGroupLauchScene crashes for SwiftData Document-Based App
I have a SwiftData document-based app. It is initialized like this: @main struct MyApp: App { @State private var showTemplatePicker = false @State private var documentCreationContinuation: CheckedContinuation<URL?, any Error>? var body: some Scene { DocumentGroup(editing: .myDocument, migrationPlan: MyMigrationPlan.self) { CanvasView() } DocumentGroupLaunchScene(Text("My App")) { NewDocumentButton("New", contentType: .canvasDocument) { try await withCheckedThrowingContinuation { continuation in documentCreationContinuation = continuation showTemplatePicker = true } } .fullScreenCover(isPresented: $showTemplatePicker) { TemplateView(documentCreationContinuation: $documentCreationContinuation) } } background: { Image("BoardVignette") .resizable() } } } extension UTType { static var canvasDocument: UTType { UTType(importedAs: "com.example.MyApp.canvas") } } Pressing the New button crashes with: #0 0x00000001d3a6e12c in (1) suspend resume partial function for closure #1 () async -> () in SwiftUI.IdentifiedDocumentGroupDocumentCreation.createNewDocument(with: SwiftUI.IdentifiedDocumentGroupConfiguration, url: Swift.Optional<Foundation.URL>, newDocumentProvider: Swift.Optional<SwiftUI.AsyncNewDocumentProvider>, _: (Swift.Optional<SwiftUI.PlatformDocument>) -> ()) -> () () All sample code that I've seen uses a FileDocument but SwiftData's setup doesn't have one so it's not completely clear how you should be using NewDocumentButton with a SwiftData file. The crash happens even before my prepareDocumentURL handler is called (I set a breakpoint and it never stops). My hunch is that the crash is because it's not able to match my contentType to a Document. Can anyone at Apple help? I don't think this use-case has been documented well.
2
1
67
May ’25
View shown by App Intent with ShowsSnippetView doesn't adapt to dark mode
I have an App Intent that conforms to ShowsSnippetView and returns a view that is shown in the Siri interface after the shortcut runs. The view simply consists of a VStack with a Text element, with no special styling. When my device is set to dark mode, the view doesn't adapt: the text is black, but the background of the Siri interface is a transparent dark gray, which makes the text almost unreadable. The text should be white in dark mode. The colorScheme environment value inside the view corresponds to light mode, even though the device is set to dark mode. This is most likely a bug in iOS.
14
0
112
May ’25