Post

Replies

Boosts

Views

Activity

How to preserve state in reference types in swiftUI
I have a SwiftUI app with a class that conforms to ObservableObject that contains state that I would like to preserve between application launches. How do I do this in swiftUI? I need something similar to @SceneStorage but for reference types. Below is an example showing what I am trying to accomplish. This app shows statistics for a specific network port. I would like to have the StreamStats parameters preserved. I can save the lastPort value using the @SceneStorage property wrapper but this is just to demonstrate the intent. Note: Although this example does not show it, the port member in StreamStats could be changed by code in the class itself. It must not only be reflected correctly the the GUI, but also be saved as part of the state. import SwiftUI @main struct SceneStorageTest: App { var body: some Scene { WindowGroup("Port Statistics", id: "statsView") { ContentView() } } } class StreamStats: ObservableObject { @Published public var port: Int = 60000 init() { startListening() } public func startListening() { print("Gathering stats for port \(port)") } } struct ContentView: View { @SceneStorage("lastPort") var lastPort: Int = 0 @StateObject var streamStats = StreamStats() @Environment(\.openWindow) private var openWindow var body: some View { VStack { Text("Last port: \(lastPort)") TextField("port", value: $streamStats.port, format: .number) Button("Open") { lastPort = streamStats.port streamStats.startListening() } Divider() Button("New Port Statistics Window") { openWindow(id: "statsView") } }.padding() } }
3
0
1.1k
Dec ’22
Where is userDefaults saved for SwiftUI Sandbox app?
I have a SwiftUI sandbox app that uses userDefaults. I would like to verify that the data is correctly saved and also modify it during development to check that my app behaves correctly. I can see the data in ~/Library/Containers//Data/Library/Preferences/.plist. My problem is that when I delete this file to check that my app will behave correctly, then it is re-created with old data. It contains entries that I used for development testing, and not in use any longer. I am unable to get a clean file again. Where is the original data saved, and how do I access it? I've looked in: ~/Library/Preferences ~/Library/Preferences/By Host ~/Library/Caches ~/Library/Saved Application State It is not in one of those locations unless it is named differently. Even a search on my mac did not find it.
6
0
3.6k
Dec ’22
Why does clean C++ sandbox app crash before reaching main?
Crash Report I have a sandboxed C++ console app that crashes before reaching main. I can reproduce the problem by starting a new, empty console application. It crashes without any changes after I select it to be a sandbox app. I have looked at this (Sandbox activated macOS application crashes immediately after execution) thread and this (Receiving this error 'EXC_BREAKPOINT') one but neither seem to be related, or give any clues. My crash log (attached) mentions "Unable to get bundle identifier for container id". I've added a Info.plist but it made no difference. What is causing this?
2
0
1.5k
Jan ’23
Why is AVAudioEngine input giving all zero samples?
I am trying to get access to raw audio samples from mic. I've written a simple example application that writes the values to a text file. Below is my sample application. All the input samples from the buffers connected to the input tap is zero. What am I doing wrong? I did add the Privacy - Microphone Usage Description key to my application target properties and I am allowing microphone access when the application launches. I do find it strange that I have to provide permission every time even though in Settings > Privacy, my application is listed as one of the applications allowed to access the microphone. class AudioRecorder { private let audioEngine = AVAudioEngine() private var fileHandle: FileHandle? func startRecording() { let inputNode = audioEngine.inputNode let audioFormat: AVAudioFormat #if os(iOS) let hardwareSampleRate = AVAudioSession.sharedInstance().sampleRate audioFormat = AVAudioFormat(standardFormatWithSampleRate: hardwareSampleRate, channels: 1)! #elseif os(macOS) audioFormat = inputNode.inputFormat(forBus: 0) // Use input node's current format #endif setupTextFile() inputNode.installTap(onBus: 0, bufferSize: 1024, format: audioFormat) { [weak self] buffer, _ in self!.processAudioBuffer(buffer: buffer) } do { try audioEngine.start() print("Recording started with format: \(audioFormat)") } catch { print("Failed to start audio engine: \(error.localizedDescription)") } } func stopRecording() { audioEngine.stop() audioEngine.inputNode.removeTap(onBus: 0) print("Recording stopped.") } private func setupTextFile() { let tempDir = FileManager.default.temporaryDirectory let textFileURL = tempDir.appendingPathComponent("audioData.txt") FileManager.default.createFile(atPath: textFileURL.path, contents: nil, attributes: nil) fileHandle = try? FileHandle(forWritingTo: textFileURL) } private func processAudioBuffer(buffer: AVAudioPCMBuffer) { guard let channelData = buffer.floatChannelData else { return } let channelSamples = channelData[0] let frameLength = Int(buffer.frameLength) var textData = "" var allZero = true for i in 0..<frameLength { let sample = channelSamples[i] if sample != 0 { allZero = false } textData += "\(sample)\n" } if allZero { print("Got \(frameLength) worth of audio data on \(buffer.stride) channels. All data is zero.") } else { print("Got \(frameLength) worth of audio data on \(buffer.stride) channels.") } // Write to file if let data = textData.data(using: .utf8) { fileHandle!.write(data) } } }
4
0
926
Jan ’25
How to create a stepper with a TextField?
I am trying to create a standard stepper with text field in swiftUI, but it does not seem to exist.I need something that looks like this:Do I have to create my own view, or is something already available?I tried an HStack with Text, TextField and stepper, but this does not align properly when placed in a form, and the stepper and text field cannot have a binding to the same value.Any ideas on how to implement this?
8
1
6.6k
Dec ’21
How do I add MenuItem to menubar in macos using SwiftUI?
The new SwiftUI introduces the new Menu - https://developer.apple.com/documentation/swiftui/menu item but I cannot find any complete examples showing how to use it. I did find an article (cannot link to it here) on how to use Menu but it is connected to a toolbar item only and does not change the menubar. I would like to add a menu item to the menubar in macOS using a SwiftUI App. Any examples of how to do this would be great.
2
0
8.5k
Feb ’21
swift Mirror not setting member values as expected
I was hoping to use swift Mirror to create an extension that can change the properties of a struct. It seems however that mutating the child items of the mirror is creating new instances and mutating those instead of the members of the method. Below is a playground that shows my problem. Can I use Mirror to achieve the goal of setting member values of structs that implement the given protocol, or should I take a different approach (and if so what)? import Cocoa struct Point { var x: Int = 0 var y: Int = 0 } protocol Shape { var origin: Point { get } } extension Shape { //: The hope is to have a generic function that will set the value of all parameters of type 'Point' but it is not working. The fact that I do not need "mutating" for this function is another clue that it will not mutate the members of the Shape. mutating func clearAllPoints() { let mirror = Mirror(reflecting: self) for child in mirror.children { // It seems the line below creates a new point instance and it is not the same member of self. if var point = child.value as? Point { point.x = 0 point.y = 0 } } } func printAllPoints() { let mirror = Mirror(reflecting: self) for child in mirror.children { if let point = child.value as? Point { print("\(child.label!) = (x: \(point.x), y: \(point.y)") } } } } struct Rectangle: Shape { var origin = Point() var corner = Point() init() { origin = Point(x: 10, y: 10) corner = Point(x: 20, y: 30) } } var rect = Rectangle() //: rect has just been initialised, and the line below correctly prints all Points as initialised. rect.printAllPoints() //: Hope is that the line below will clear all Points but ... rect.clearAllPoints() //: ... it does not. The line below prints all Points with exactly the same values. rect.printAllPoints()
0
1
760
Jul ’22
Why does custom Binding not update UI
I have a class that I cannot change to ObservableObject with Published members. I tried getting around this by writing my own Binding. Although the value is updated correctly, the UI is not. Why is this. Below is a simple demo view. When it is run and the toggle is clicked, it will print out correctly that the value is changed, but the UI does not update. Why? import SwiftUI class BoolWrapper {   public var value = false {     didSet {       print("Value changed to \(value)")     }   } } let boolWrapper = BoolWrapper() struct ContentView: View {   var body: some View {     Toggle(isOn: Binding(get: {       return boolWrapper.value     }, set: { value in       boolWrapper.value = value     }), label: { Text("Toggle") })   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } }
5
0
4.8k
Mar ’24
Using TextField:text:selection crashes on macOS
I am trying out the new TextField selection ability on macOS but it crashes in various different ways with extremely large stack traces. Looks like it is getting into re-entrant function calls. A similar problem is described on the SwiftUI forums with no responses yet. Here is my simple example struct ContentView: View { @State private var text: String = "" @State private var selection: TextSelection? var body: some View { TextField("Message", text: $text, selection: $selection) .padding() } } Setting text to a value like "Hallo World" causes an instant crash as soon as you start typing in the TextField. Setting text empty (as in example above) lets you edit the text but as it crashes as soon as you commit it (press enter). Any workarounds or fixes?
4
1
531
Dec ’24
How to preserve TextField cursor position when replacing text
I am doing text replacement in a SwiftUI TextField as the user types. This works fine when the cursor is at the end of the input, but fails when the user moves the cursor to the middle and start typing. As soon as a correction is made, the cursor jumps to the end of the string moving the user's cursor away from where they were editing. Below is a simple example of a view doing text replacement. Is it possible to get the cursor position inside the onChange modifier, and preserve it without custom wrapping a UITextView. I've done that, and it creates other problems. struct ContentView: View { @State private var input: String = "" var body: some View { VStack { TextField("", text: $input) .onChange(of: input) { input = input.replacingOccurrences(of: "*", with: "×") input = input.replacingOccurrences(of: "/", with: "÷") input = input.replacingOccurrences(of: "pi", with: "π") } } .padding() } }
0
2
1.5k
Feb ’24
SwiftUI Table with TextField becomes unresponsive as entries increase
I am trying to implement a simple Table with a TextField that makes it possible to edit the data. Below is a very simple example where I am trying to do this. It works, but it becomes very unresponsive as the number of people increases. The example as it is, has 1,000 people. It is very slow when a TextField gets focus and is used to edit something. Strangely, it also gets very slow when you scroll through an entry that has been edited. It crashes completely when 10,000 people is used. I found this similar question on the web, but it is not answered. What should I do to implement an editable Table like this? struct ContentView: View { struct Person: Identifiable { var givenName: String var familyName: String let id = UUID() } @State private var people = [Person].init(repeating: Person(givenName: "Name", familyName: "Family"), count: 1000) var body: some View { Table($people) { TableColumn("Given Name") { $person in TextField("Name", text: $person.givenName) } TableColumn("Family Name") { $person in TextField("Family Name", text: $person.familyName) } TableColumn("Full Name") { $person in Text("\(person.givenName) \(person.familyName)")} } } }
1
3
2.2k
Oct ’23
Can I bind to Int but edit with TextField
My question is slightly broader, but hopefully this simple use case states the point.I ofthen run in to the problem where my source of truth is a custom type (struct, array of bytes, int, etc.) that I want to edit. I would like to write a view that has a binding to this type so that all the editing logic lives inside this view without the views outside having to worry how it is edited.The simplest example of this is a view that takes a binding to an Int where the user edits it with a TextField. Up to now I've only been able to do this with a custom UI- or NSViewRepresentable implementation. I thought I had a solution today, but it too does not work. It is close enough, that I thought maybe someone can see a path going further.Below is my code. It has an IntView that takes a binding to an Int, and uses state for the strValue. When it first apears, it updates the local state. It then has a method that can be called to update the binding value (this because I cannot get updates as the text field is changing).My contentView creates this view and stores updateValue so that it can be called when the button is pressed. The problem is that view is a value (not a reference), so the intView created in body() is not the same one as that in the .async call (I double-checked this with the print that prints the pointer to each). When updateValue() is called, I get an exception, because I am using the wrong view. The reason for using an .async call is so that I do not change state when body is computed.Can this code somehow be made to work, or is there another solution to writing IntView that takes a binding to an Int?My problem is often more complicated for example when I want to bind to a struct. If I write a custom __ViewRepresentable solution, then I lose a lot of the ease-of-use of swift, and goes back to manual layout, etc.struct IntView: View { @Binding var value: Int @State private var strValue: String = "" var body: some View { return TextField("Type here", text: $strValue) .onAppear(perform: { self.strValue = "\(self.value)" }) } func updateValue() { value = Int(strValue)! } } struct ContentView: View { @State var intValue: Int = 12 @State var updateValue: (() -&gt; Void)? var body: some View { let intView = IntView(value: $intValue) withUnsafePointer(to: intView) { print("value at first @\($0)") } DispatchQueue.main.async { withUnsafePointer(to: intView) { print("value in async @\($0)") } self.updateValue = intView.updateValue } return VStack { Text("\(intValue)") intView Button(action: { self.updateValue!() }, label: { Text("Get Value") }) } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
6
0
6k
Apr ’22
How to remove SwiftUI TextField focus border?
How does one remove the focus border for a TextField in SwiftUI?In Cocoa, setting the border to "None" in interface builder would remove the border.I've tried using .border with a width of zero, but that does not work. The .border adds another border on top of the focus border.Setting the style also does not do the trick.
2
0
5.3k
Aug ’23