Posts

Post marked as solved
5 Replies
2.5k Views
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()   } }
Posted
by oreman.
Last updated
.
Post not yet marked as solved
0 Replies
88 Views
I am trying to get SwiftUI views to move from one position to another using animation. I know that when the identity of the views change this often result in a fade instead of an animation but I do not believe this is happening in my case. Below is a simple example program with four views from a 2D array (the 2D array is important). There is a button to rotate the views clockwise. I tried using two ForEach blocks but I cannot use it on the outer one because the row arrays does not conform to Identifiable. I also changed my code to write out the views explicitly without the ForEach blocks but I get the same result: The column changes animate as movement but the row changes animate as fades. How do I get it to animate all four views moving clockwise? import SwiftUI struct Block: Identifiable { var id : Int = 0 } struct Board { let numRows = 2 let numCols = 2 var blocks: [[Block]] init() { blocks = Array(repeating: Array(repeating: Block(), count: numCols), count: numRows) for row in 0..<numRows { for col in 0..<numCols { blocks[row][col].id = row * numCols + col } } } mutating func rotate() { let temp = blocks[0][0] blocks[0][0] = blocks[1][0] blocks[1][0] = blocks[1][1] blocks[1][1] = blocks[0][1] blocks[0][1] = temp } } struct BlockView: View { var block: Block var body: some View { ZStack { Rectangle() .fill(Color.secondary) Text("\(block.id)") .font(.largeTitle) } .aspectRatio(1.0, contentMode: .fit) } } struct ContentView: View { @State var board = Board() var body: some View { VStack { Button("Rotate") { withAnimation(.easeInOut(duration: 1.0)) { board.rotate() } } VStack { ForEach(0..<2) { row in HStack { ForEach(board.blocks[row]) { block in BlockView(block: block) } } } } } .padding() } } #Preview { ContentView() }```
Posted
by oreman.
Last updated
.
Post not yet marked as solved
0 Replies
368 Views
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() } }
Posted
by oreman.
Last updated
.
Post not yet marked as solved
1 Replies
1.4k Views
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)")} } } }
Posted
by oreman.
Last updated
.
Post marked as solved
2 Replies
3.8k Views
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.
Posted
by oreman.
Last updated
.
Post not yet marked as solved
1 Replies
676 Views
I feel a bit dumb asking for help because it is clear that git integration in XCode should just work, but it never worked for me and I hope someone can help. I can see some more work went into XCode 15 Beta but it is not working well their either. It always sort-of worked, but many features are just broken. I can do basic commits and push to a remote but almost everything else is broken. The following basic things does not work: Upstream changes are never shown. It shows that I am behind but there is nothing I can do about it. Pull does not work. When I select "Pull" it shows "Loading..." in the dropdown. Pressing the Pull button dismisses the dialog, but does nothing. I have top pull from the command line, or use external app. It does not show my current position in a repo correctly. Neither in my current branch, or when I look at the remotes (origin). Refresh and Fetch has no effect. I can switch to a different point in the branch, but the display does not show me that it happened. I can however confirm with command line or external tool that it worked (and obviously the code). I did a very simple test where I made a local repo on the file system. I then cloned two projects from it, and used it to test the above. It works perfectly from command line, or Sourcetree, but not from XCode. What am I doing wrong? I've read all the help from apple and various guides but clearly I am doing something wrong. It would have been nice if I did not have to switch my tools.
Posted
by oreman.
Last updated
.
Post not yet marked as solved
1 Replies
276 Views
We have a very large project that consists of 1000+ source files that builds 20+ targets (libraries and different versions of our app). Most is C++. We recently started having problems with intenseness. The strange thing is that compiling and navigation works but simple code completion is suddenly very broken. I manage to narrow it down to a simple use-case by deleting all the targets but one, and all the source files but two. I have a simple main.cpp that includes one header file test.h. If test.h is in the same folder as main.cpp, then intellisense works, but placing it in any other folder (all part of my project), intellisense stops working. I've re-created this simple project from scratch, reproducing the file structure. Intellisense would work in this case. I could open the two projects side by side and went through all project and target settings and they were all identical, but the one from our original project does not work. Can it be that the project contains something corrupt that was built up over the years? I really do not want to create the entire project and targets again from scratch. I've done all the tricks I could find on the forums (Removing Derived folder; opening and closing Xcode; etc.). Nothing works, except apparently creating the project from scratch. The problem is also present in latest Xcode 15 Beta. Any ideas on how to fix this?
Posted
by oreman.
Last updated
.
Post marked as solved
2 Replies
1k Views
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?
Posted
by oreman.
Last updated
.
Post marked as solved
3 Replies
666 Views
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() } }
Posted
by oreman.
Last updated
.
Post marked as solved
6 Replies
1.6k Views
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.
Posted
by oreman.
Last updated
.
Post marked as solved
1 Replies
668 Views
I have a simple app with a sidebar listing items and an edit view to edit the details of the selected item. One of the parameters that can be changed in the edit view is the name of the item that is also shown in the sidebar. Below is a simple app demonstrating the problem. It lits 4 people and you can change the name. When you change the name, the sidebar does not change until another is selected. I would like the name in the sidebar to change as it is edited. If I added a text view in the edit view, then it would change as the TextField changes. Why does the item in the sidebar not change (or only change when selecting different item)? 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 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         Text(person.name)       }.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)   } }
Posted
by oreman.
Last updated
.
Post marked as solved
2 Replies
1.1k Views
I have a simple List with nested children forming a tree. Each item can be checked. If all children are checked (or not) then the parent must reflect this state. It must also be possible to change the state of the children by selecting the parent. Below is a simple example that sort-of works. When you change the state of a parent, the state of all the children change as well. But how do I make it work the other way around so that the parent is notified when a child changes? When all the children are checked, the parent should be checked. I cannot get a reference to the parent. I tried adding handlers but that captures self (the parent) in an escaping closure that mutates it. I created a timer for each item that would periodically check the children but this just feels very wrong. I do not want to convert all the value-type coding to reference types but I cannot find an elegant way of solving this problem. Any suggestions will be greatly appreciated. import SwiftUI struct Item: Identifiable { var id = UUID() var name: String var isSelected: Bool = false { didSet { guard children != nil else { return } for i in 0..<children!.count { children![i].isSelected = isSelected } } } var children: [Item]? } struct ContentView: View { @Binding var itemsTree: [Item] var body: some View { List($itemsTree, children: \.children) { $item in Toggle(item.name, isOn: $item.isSelected) } } } @main struct ListQuestionApp: App { @State private var itemTree: [Item] = [ Item(name: "Level 1", children: [ Item(name: "Level 2", children: [ Item(name: "Item B"), Item(name: "Item A") ]) ]) ] var body: some Scene { WindowGroup { ContentView(itemsTree: $itemTree) } } }
Posted
by oreman.
Last updated
.
Post not yet marked as solved
7 Replies
2k Views
I have an application that communicates with custom external hardware on the network (using UDP). I have a thread that receives and process the UDP data and then signals a waiting thread by releasing a semaphore when data is available. A have a asyncSendAndReceive and asyncReceive function that just begs to use async/await. But I cannot simply switch because of the use of the semaphore. Various forums and discussions said that semaphores should no longer be used for signalling. If not semaphores, then what else? Note that my two async functions may not always block. If data was received before they were called, then it is queued (and the semaphore is signalled).
Posted
by oreman.
Last updated
.
Post not yet marked as solved
0 Replies
465 Views
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()
Posted
by oreman.
Last updated
.
Post marked as solved
1 Replies
1.7k Views
I've been trying to wrap a UITextField in UIViewRepresentable in order to do some customisation but this does not seem to work. My main issue is that the frame of the UITextField is wrong. I even raised a TSI for this. It was confirmed to be a bug (I raised a bug report) but was told that the only work around is effectively to completely re-write my own Text Field using the basics. I cannot believe something as simple as this has not been solved yet. Below is my minimum code to show the problem. I've tried a lot of things: adding InputView to a ScrollView; constraining the frame of InputView, etc. The problem is that when you keep on typing to fill the UITextField then it's frame gets a negative x-offset and it goes off the screen so that you can no longer see the cursor. How do I fix this, or do I really have no choice but to re-write UITextField? import SwiftUI struct InputView: UIViewRepresentable { let fontName = "Arial" let fontSize: CGFloat = 32.0 @Binding var text: String typealias UIViewType = UITextField func makeUIView(context: Context) -> UIViewType { // Setup text view: // ---------------- let textView = UITextField() textView.delegate = context.coordinator // Creae a dummy view for the inputView (keyboard) so that the default // keyboard is not shown: let dummyView = UIView(frame: CGRect.zero) textView.inputView = dummyView return textView } func makeCoordinator() -> InputView.Coordinator { return Coordinator(self) } func updateUIView(_ textView: UIViewType, context: Context) { if textView.text != text { textView.text = text } } class Coordinator: NSObject, UITextFieldDelegate { var parent: InputView init(_ parent: InputView) { self.parent = parent } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let currentValue = textField.text as NSString? { let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String self.parent.text = proposedValue } return true } } } struct ContentView: View { @State private var text: String = "Type here" var body: some View { VStack { InputView(text: $text) Text(text) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Posted
by oreman.
Last updated
.