Post

Replies

Boosts

Views

Activity

Reply to SwiftUI TextField corrupts selection when inserting utf16
I tried my code in MacOS 26.0 Beta (25A5279m). The problem is not there, so it seems to be a bug in 15.5. Although this specific issue is fixed in 26.0, it is introducing new ones. The index in the string is clearly being corrupted. I suspect it still has to do between the switch of index between utf8 and utf16. When I type 1234, then press cursor back once, so that curser is between 3 and 4, and type '' three times then I suddenly get '12×3×à 4'. I can see from my log that the input is completely corrupted: input: changed from '' to '1' input: changed from '1' to '12' Moving cursor from 2[any] Moved to 4[utf8] input: changed from '12' to '12×' input: changed from '12×' to '12×3' input: changed from '12×3' to '12×34' Moving cursor from 4[utf16] Moved to 7[utf8] input: changed from '12×34' to '12×3×4' Moving cursor from 7[utf8] Moved to 8[utf8] input: changed from '12×3×4' to '12×3××4' Moving cursor from 8[utf8] Moved to 9[utf8] input: changed from '12×3××4' to '12×3×\303×\2274' code-block It seems that the text selection in TextField is not great yet. I wanted to raise a developer support but it said that apple engineers will prioritise forums during this time. Hopefully someone can take a look at this. I also tried changing from String to AttributedString to test the new TextField with formatting but this does not seem to be available yet.
Topic: UI Frameworks SubTopic: SwiftUI
Jun ’25
Reply to SwiftUI TextField corrupts selection when inserting utf16
Thank you for the reply. That is strange. I consistently get the error. I am running macOS 15.4.1 (24E263). I've updated the body variable in my original example to print out all the changes (see further below, from line 7). With this change, I get the following output: input: changed from '' to '1' input: changed from '1' to '12' Moving cursor from 2[any] Moved to 4[utf8] input: changed from '12' to '12×' input: changed from '12×' to '12×3' input: changed from '12×3' to '12×43' Note line 3&4 where it replaced '*' with 'x'. When I then continue to type '3' and '4' you can see the output changes to "43" instead of "34". Your log showed the cursor moving twice. Did you use the arrow keys for this? I only have the cursor moving once for the one replacement. var body: some View { VStack { TextField("Type 12*34", text: $input, selection: $selection) .onKeyPress(action: {keyPress in handleKeyPress(keyPress) }) .onChange(of: input) { oldValue, newValue in print("input: changed from '\(oldValue)' to '\(newValue)'") } Text("Selection: \(selectionAsString())") }.padding() }
Topic: UI Frameworks SubTopic: SwiftUI
May ’25
Reply to Why is AVAudioEngine input giving all zero samples?
Hi Greg, Thank you very much. Knowing that the code is not the issue gave me enough to resolve the issue. It is a macOS Sandbox app and Audio Input was not checked. The app now also stopped asking me for permission every time when it runs. I still get the following warnings traced when the app runs. It seems to have no effect. Can I safely ignore it? AddInstanceForFactory: No factory registered for id <CFUUID 0x600002d100e0> F8BB1C28-BAE8-11D6-9C31-00039315CD46 HALC_ProxyObjectMap.cpp:173 HALC_ProxyObjectMap::_CopyObjectByObjectID: failed to create the local object HALC_ShellDevice.cpp:2670 HALC_ShellDevice::RebuildControlList: couldn't find the control object throwing -10877 throwing -10877 86275 HALC_ProxyIOContext.cpp:1073 HALC_ProxyIOContext::_StartIO(): Start failed - StartAndWaitForState returned error 35 86275 HALC_ProxyIOContext.cpp:1073 HALC_ProxyIOContext::_StartIO(): Start failed - StartAndWaitForState returned error 35 86275 HALC_ProxyIOContext.cpp:1073 HALC_ProxyIOContext::_StartIO(): Start failed - StartAndWaitForState returned error 35 HALB_IOThread.cpp:326 HALB_IOThread::_Start: there already is a thread
Topic: Media Technologies SubTopic: Audio Tags:
Dec ’24
Reply to Using TextField:text:selection crashes on macOS
Follow-up, but related question. I expanded my demo, playing with TextField(text:selection) to understand it and found that the selection changes before the text does. Below is my expanded file. I tried to print the selection underneith the TextField but this code crashes. I've added print statements to debug and found that the selection is not valid for the value of text when I call toString. Is this normal? I found that using the onChange event on the selection works correctly but I see this as a workaround. It means there is currently no way to just print the selection (current state) with the corresponding text (same state) in the view, or am I missing something? struct ContentView: View { @State private var selection: TextSelection? @State private var text: String = "" var body: some View { VStack { TextField("Message", text: $text, selection: $selection) // .onChange(of: selection) { // if let selection = selection.take() { // if case let .selection(range) = selection.indices { // print("Selection in \(text): \(toString(selection: selection))") // print("Selected text: '\(text[range])'") // } // } // } Text("Selection in \(text): \(toString(selection: selection))") } .padding() } func toString(selection: TextSelection?) -> String { guard let selection else { return "None" } print("Printing indices in '\(text)'") switch selection.indices { case .selection(let range): let lower = range.lowerBound.utf16Offset(in: text) let upper = range.upperBound.utf16Offset(in: text) return "\(lower) - \(upper)" case .multiSelection(let rangeSet): return "Multi selection \(rangeSet)" @unknown default: fatalError("Unknown selection") } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’24
Reply to Protocol availability inconsistencies related to modern serial layers
How (where) is the best place to push for this functionality? I know it was always possible with lightning (hardware wise) but the move to USB-C opened up so many easy, low-hanging-fruit possibilities. I can plug in my standard USB-thumb drive into my iPhone and share files; I can plug in my existing USB-C to Ethernet and use Ethernet; I can even plug in my smart monitor. As a developer (hardware and software) it would be awesome to plug and access standard HID and serial (like FTDI) devices. Test jigs, test stations, etc. can suddenly use iPhones instead of PCs.
Topic: App & System Services SubTopic: Core OS Tags:
Oct ’23
Reply to Can corrupt Xcode project explain broken intellisense?
I dug a bit deeper and found more info. It does not seem to be a corrupt Xcode project, but a setting in the top level project. I found that the issue is caused with Header Search Paths. We unfortunately have one or two places where there are file name clashes. To get around this, we set Use Header Maps to No and each target has the correct Header Search Paths to find the correct file. It turns out that this is causing the issue. Attached is an image of a very simple project (cannot attach project) to demonstrate the issue. The image should make it pretty clear on how to reproduce the project. The project contains two targets. The SearchPathIssue Intellisense Working target has Use Header Maps set to Yes (default) while SearchPathIssue Intellisense Broken has it set to No and has a Header Search Path to correctly find the headers. If the search path is not given, then the project does not build. If you open main.cpp you can type "shape." to see the code completions. It works when the target SearchPathIssue Intellisense Working is selected and it does not work when SearchPathIssue Intellisense Broken is selected. I do not have a work-around for the issue yet. Maybe someone does? I've raised a bug using Feedback Assistant and will post here if I get a reply.
Jun ’23
Reply to Why does clean C++ sandbox app crash before reaching main?
Thank you. Afraid the error must have been between keyboard and chair. I got the error on an existing, older project. Then I created a new, clean C++ project and it did the same. Not sure what I managed to do to enable sandbox for a console app, but I thought it was the default setting, hence the question. I just tried reproducing it again just now, and could not. When I created a new app, I got the clean "Hallo World". So seems it was just an error on my side. At least I learned something - thank you for that.
Topic: Code Signing SubTopic: General Tags:
Jan ’23
Reply to How to preserve state in reference types in swiftUI
Thanks to apple support for helping me out with this one. The correct answer is in the WWDC22 The SwiftUI cookbook for navigation video, right at the end. For completeness, the following fixes the example given in the original question: import SwiftUI import Combine @main struct SceneStorageTest: App { var body: some Scene { WindowGroup("Port Statistics", id: "statsView") { ContentView() } } } class StreamStats: ObservableObject, Encodable { @Published public var port: Int = 60000 public var jsonData: Data? { get { try? JSONEncoder().encode(self) } set { guard let data = newValue, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return } port = json["port"] as! Int } } enum CodingKeys: String, CodingKey { case port } init() { startListening() } public func startListening() { print("Gathering stats for port \(port)") } var objectWillChangeSequence: AsyncPublisher<Publishers.Buffer<ObservableObjectPublisher>> { objectWillChange .buffer(size: 1, prefetch: .byRequest, whenFull: .dropOldest) .values } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(port, forKey: .port) } } struct ContentView: View { @StateObject var streamStats = StreamStats() @SceneStorage("streamStatsData") var streamStatsData: Data? @Environment(\.openWindow) private var openWindow var body: some View { VStack { TextField("port", value: $streamStats.port, format: .number) Button("Open") { streamStats.startListening() } Divider() Button("New Port Statistics Window") { openWindow(id: "statsView") } } .padding() .task { if let data = streamStatsData { print("Loading data.") streamStats.jsonData = data } for await _ in streamStats.objectWillChangeSequence { streamStatsData = streamStats.jsonData } } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’22
Reply to Where is userDefaults saved for SwiftUI Sandbox app?
Aaah great, case closed. At least the world makes sense again. I've marked your first reply as correct, as it answered my question but this extra bit of information clears up some confusion that made me think it is not stored there. The full answer may have been that it is stored in ~/Library/Containers but also cached. This may only be useful for development purposes.
Topic: App & System Services SubTopic: General Tags:
Dec ’22
Reply to Where is userDefaults saved for SwiftUI Sandbox app?
The preferences file that backs UserDefaults is ~/Library/ ... Thanks. That is what I've been looking at. The part that confuses me is that I can remove the container, empty my bin, run my app again, and then the file contains data that I did not write with the last run of my app. It contains values that was written by earlier versions of the app. So it seems like it is refreshing the container from some cache that I've not been able to find. Am I seeing ghosts, or do I misunderstand how it should be working? WARNING The location and format of this file is subject to change. ... but do not encode such knowledge in your product. Understood. That was my intention - to get a better understanding of what is saved, and to check that it is saved correctly. I was working with arrays of dictionaries where each dictionary had a UUID so making errors in code and debugging without looking at the underlying data was very tricky. For more info about that tool, see the defaults man page. I've used the defaults tools. I could see for example that when I removed the container that defaults would show that it no longer sees the data. But just like opening the .plist file in GUI, defaults showed the same stale data returning when I run my app again. Hmmmm, that’s not good. Please get in touch with me via email Thanks, will do.
Topic: App & System Services SubTopic: General Tags:
Dec ’22
Reply to How to preserve state in reference types in swiftUI
I quickly played with UserDefaults but as expected it gets saved in Preferences .plist file. I did see keys with names like "AppWindow-X" [1]. If I could get the number of a window in a scene that would uniquely identify it, then I could use that to store the settings specific for the window but I found no way of getting a window reference. For interest sake, I also tried to find where the @SceneStorage data is stored to see if it gave any clues but I could not find it. Any suggestions will be appreciated. [1] Where X is the window number.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Nov ’22
Reply to Why does SwiftUI sidebar not update when ObservedObject changes?
The problem is that person is never observed. The Text view in the list will not be notified when the person's name changes because it is not observed. To fix the problem, create another view that observes the class (ObservableObject). That entire view is invalidated when the @Published field in the @ObservedObject changes. The code below fixes the problem and the sidebar is correctly updated in real time as the name is edited. class Person: NSObject, ObservableObject { @Published public var name: String init(name: String) { self.name = name } } class Database { public var people: [Person] init() { people = [Person(name: "Susan"), Person(name: "John"), Person(name: "Jack"), Person(name: "Mary")] } } @main struct BindingTestApp: App { @State private var database = Database() var body: some Scene { WindowGroup { ContentView(people: $database.people) } } } struct PersonView: View { @ObservedObject var person: Person var body: some View { Text(person.name) } } struct ContentView: View { struct SidebarView: View { @Binding var people: [Person] @Binding var selectedPerson: Person? var body: some View { List(people, id: \.self, selection: $selectedPerson) { person in PersonView(person: person) }.listStyle(SidebarListStyle()) } } struct PersonView: View { @ObservedObject public var person: Person var body: some View { TextField("Name", text: $person.name) } } @Binding var people: [Person] @State private var selectedPerson: Person? var body: some View { NavigationView { SidebarView(people: $people, selectedPerson: $selectedPerson) if let selectedPerson = selectedPerson { PersonView(person: selectedPerson) } else { Text("Please select or create a person.") } } } } struct ContentView_Previews: PreviewProvider { @State static private var database = Database() static var previews: some View { ContentView(people: $database.people) } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Nov ’22