Post

Replies

Boosts

Views

Activity

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.4k
Aug ’23
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.7k
Dec ’21
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: (() -> 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
6.1k
Apr ’22
Disable Line Wrapping in UITextView wrapped in UIViewRepresentable
I need to do a bit of customisation on a UITextView so I am creating a custom UIViewRepresentable to wrap the UITextView. One of these is that the input should be centred and not wrap. Searching on how to disable wrapping gives various conflicting recommendations, from not using UITextView to wrapping it in a UIScrollView. None of these seem to work reliably. It seems like all that is required, is setting the size of the text container to be sufficiently wide but this is also not working. Below is what I've tried so far but it does not wrap the view. The InputView also seems to take up the entire height of the screen. I have a feeling this is fundamentally part of my problem. What am I missing? import SwiftUI struct InputView: UIViewRepresentable {   @Binding var text: String   typealias UIViewType = UITextView   func makeUIView(context: Context) -> UIViewType {     // Setup text view:     // ----------------     let textView = UITextView()     textView.textAlignment = .center     textView.delegate = context.coordinator     textView.font = UIFont.systemFont(ofSize: 72)          textView.textContainer.widthTracksTextView = false     textView.textContainer.size = CGSize(width: 20000, height: CGFloat.greatestFiniteMagnitude)     textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]          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, UITextViewDelegate {     var parent: InputView          init(_ parent: InputView) {       self.parent = parent     }          func textViewDidChange(_ textView: UITextView) {       parent.text = textView.text     }   } } struct ContentView: View {   @State private var input: String = "ShouldNotWrapButScrollHorizontally"      var body: some View {     InputView(text: $input)       .padding()   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } }
1
0
2.7k
Oct ’21
How do I get recommended iOS app preview resolution?
Reading other questions and searching on the web, I am clearly missing something very obvious. I am trying to make an app preview video for iOS. I've followed Creating Videos for App Previews to record a video on my iPhone 13. This gives me a video with a resolution of 2532 x 1170 (as expected). The App preview specifications states that the native iPhone 13 resolution is 2436 x 1125 and that the accepted resolution is 1920 x 886. Why is the app preview specification native resolution different from the actual iPhone 13 resolution? Am I missing some insets? When I use Quick Time to save my video as 1080p then I get an output resolution of 1920 x 888 (it seems to be rounding up since the perfect scale would have been 1920 x 887,2037915). I am unable to see how I can get to the accepted native resolution of 2436 x 1125 or how I can resample it to 1920 x 886. I get the exact same results using the simulator. How do I create a preview video in the accepted resolutions?
1
0
1.9k
Jan ’22
Cannot bind to local UDP socket - address already in use
I have some code that used to work but is failing to bind to a local UDP port saying it is already in use. lsof does not show that the port is being used. Below is my receive function that fails. bindResult is "-1" when calling bind, and the error printed out contains "Address already in use (48)". I am trying to bind to 127.0.0.1:6000. This has been working for a very long time, but I've not used it for one or two months, so not sure if a macOS upgrade or something else broke it. func receive(handleRxData: @escaping (UdpSocket, IpAddress, ArraySlice<UInt8>) -> Void,                withError error: (_ msg: String) -> Void) {          self.handleRxData = handleRxData          var cfSocketContext = CFSocketContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)     cfSocketContext.info = Unmanaged.passRetained(self).toOpaque()          cfSock = CFSocketCreate(kCFAllocatorDefault,                             PF_INET,                             SOCK_DGRAM,                             IPPROTO_UDP, CFSocketCallBackType.readCallBack.rawValue,                             { (socket: CFSocket?, callBackType: CFSocketCallBackType, address: CFData?, data: UnsafeRawPointer?, info: UnsafeMutableRawPointer?) -> Void in                               let udpSocket = Unmanaged<UdpSocket>.fromOpaque(info!).takeUnretainedValue()                               udpSocket.receiveCallback()     },                             UnsafeMutablePointer<CFSocketContext>(&cfSocketContext))     let sock = CFSocketGetNative(cfSock)          // Create ipv4 addr struct:     var sin = sockaddr_in()     if (local.type == .ipv4) {       sin.sin_len = __uint8_t(MemoryLayout.size(ofValue: sin))       sin.sin_family = sa_family_t(AF_INET)       sin.sin_addr.s_addr = local.ipv4.bigEndian       sin.sin_port = local.port.bigEndian     }          let bindResult = withUnsafeMutablePointer(to: &sin) {       $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {         bind(sock, UnsafeMutablePointer<sockaddr>($0), socklen_t(MemoryLayout<sockaddr_in>.size))       }     }     if bindResult < 0 {       error("Could not bind to socket \(sin) ( \(String(cString: strerror(errno)!)) (\(errno)).")       return     }          // Change socket to non-blocking:     let flags = fcntl(sock, F_GETFL);     let fcntlResult = fcntl(sock, F_SETFL, flags | O_NONBLOCK);     if (fcntlResult < 0) {       print("Could not change socket to non-blocking ( \(String(cString: strerror(errno)!)) (\(errno)).")     }     // Add to run loop:     let rls = CFSocketCreateRunLoopSource(nil, cfSock, 0);     if (rls == nil) {       error("Could not get run loop source.")       return     }     CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, CFRunLoopMode.commonModes)// CFRunLoopMode.defaultMode);   }
3
0
3.0k
Feb ’22
Does UITextField in UIViewRepresentable have a solution?
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() } }
1
0
2.9k
Apr ’22
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
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
777
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.9k
Mar ’24
Why does SwiftUI sidebar not update when ObservedObject changes?
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)   } }
1
0
1k
Nov ’22
How to use network sockets with async/await?
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).
9
0
3.8k
Jul ’24
How to access parent in List View with children?
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) } } }
2
0
1.9k
Nov ’22
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.2k
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.7k
Dec ’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.
Replies
2
Boosts
0
Views
5.4k
Activity
Aug ’23
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?
Replies
8
Boosts
1
Views
6.7k
Activity
Dec ’21
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() } }
Replies
6
Boosts
0
Views
6.1k
Activity
Apr ’22
Disable Line Wrapping in UITextView wrapped in UIViewRepresentable
I need to do a bit of customisation on a UITextView so I am creating a custom UIViewRepresentable to wrap the UITextView. One of these is that the input should be centred and not wrap. Searching on how to disable wrapping gives various conflicting recommendations, from not using UITextView to wrapping it in a UIScrollView. None of these seem to work reliably. It seems like all that is required, is setting the size of the text container to be sufficiently wide but this is also not working. Below is what I've tried so far but it does not wrap the view. The InputView also seems to take up the entire height of the screen. I have a feeling this is fundamentally part of my problem. What am I missing? import SwiftUI struct InputView: UIViewRepresentable {   @Binding var text: String   typealias UIViewType = UITextView   func makeUIView(context: Context) -> UIViewType {     // Setup text view:     // ----------------     let textView = UITextView()     textView.textAlignment = .center     textView.delegate = context.coordinator     textView.font = UIFont.systemFont(ofSize: 72)          textView.textContainer.widthTracksTextView = false     textView.textContainer.size = CGSize(width: 20000, height: CGFloat.greatestFiniteMagnitude)     textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]          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, UITextViewDelegate {     var parent: InputView          init(_ parent: InputView) {       self.parent = parent     }          func textViewDidChange(_ textView: UITextView) {       parent.text = textView.text     }   } } struct ContentView: View {   @State private var input: String = "ShouldNotWrapButScrollHorizontally"      var body: some View {     InputView(text: $input)       .padding()   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } }
Replies
1
Boosts
0
Views
2.7k
Activity
Oct ’21
How do I get recommended iOS app preview resolution?
Reading other questions and searching on the web, I am clearly missing something very obvious. I am trying to make an app preview video for iOS. I've followed Creating Videos for App Previews to record a video on my iPhone 13. This gives me a video with a resolution of 2532 x 1170 (as expected). The App preview specifications states that the native iPhone 13 resolution is 2436 x 1125 and that the accepted resolution is 1920 x 886. Why is the app preview specification native resolution different from the actual iPhone 13 resolution? Am I missing some insets? When I use Quick Time to save my video as 1080p then I get an output resolution of 1920 x 888 (it seems to be rounding up since the perfect scale would have been 1920 x 887,2037915). I am unable to see how I can get to the accepted native resolution of 2436 x 1125 or how I can resample it to 1920 x 886. I get the exact same results using the simulator. How do I create a preview video in the accepted resolutions?
Replies
1
Boosts
0
Views
1.9k
Activity
Jan ’22
Cannot bind to local UDP socket - address already in use
I have some code that used to work but is failing to bind to a local UDP port saying it is already in use. lsof does not show that the port is being used. Below is my receive function that fails. bindResult is "-1" when calling bind, and the error printed out contains "Address already in use (48)". I am trying to bind to 127.0.0.1:6000. This has been working for a very long time, but I've not used it for one or two months, so not sure if a macOS upgrade or something else broke it. func receive(handleRxData: @escaping (UdpSocket, IpAddress, ArraySlice&lt;UInt8&gt;) -&gt; Void,                withError error: (_ msg: String) -&gt; Void) {          self.handleRxData = handleRxData          var cfSocketContext = CFSocketContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)     cfSocketContext.info = Unmanaged.passRetained(self).toOpaque()          cfSock = CFSocketCreate(kCFAllocatorDefault,                             PF_INET,                             SOCK_DGRAM,                             IPPROTO_UDP, CFSocketCallBackType.readCallBack.rawValue,                             { (socket: CFSocket?, callBackType: CFSocketCallBackType, address: CFData?, data: UnsafeRawPointer?, info: UnsafeMutableRawPointer?) -&gt; Void in                               let udpSocket = Unmanaged&lt;UdpSocket&gt;.fromOpaque(info!).takeUnretainedValue()                               udpSocket.receiveCallback()     },                             UnsafeMutablePointer&lt;CFSocketContext&gt;(&amp;cfSocketContext))     let sock = CFSocketGetNative(cfSock)          // Create ipv4 addr struct:     var sin = sockaddr_in()     if (local.type == .ipv4) {       sin.sin_len = __uint8_t(MemoryLayout.size(ofValue: sin))       sin.sin_family = sa_family_t(AF_INET)       sin.sin_addr.s_addr = local.ipv4.bigEndian       sin.sin_port = local.port.bigEndian     }          let bindResult = withUnsafeMutablePointer(to: &amp;sin) {       $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {         bind(sock, UnsafeMutablePointer&lt;sockaddr&gt;($0), socklen_t(MemoryLayout&lt;sockaddr_in&gt;.size))       }     }     if bindResult &lt; 0 {       error("Could not bind to socket \(sin) ( \(String(cString: strerror(errno)!)) (\(errno)).")       return     }          // Change socket to non-blocking:     let flags = fcntl(sock, F_GETFL);     let fcntlResult = fcntl(sock, F_SETFL, flags | O_NONBLOCK);     if (fcntlResult &lt; 0) {       print("Could not change socket to non-blocking ( \(String(cString: strerror(errno)!)) (\(errno)).")     }     // Add to run loop:     let rls = CFSocketCreateRunLoopSource(nil, cfSock, 0);     if (rls == nil) {       error("Could not get run loop source.")       return     }     CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, CFRunLoopMode.commonModes)// CFRunLoopMode.defaultMode);   }
Replies
3
Boosts
0
Views
3.0k
Activity
Feb ’22
Does UITextField in UIViewRepresentable have a solution?
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() } }
Replies
1
Boosts
0
Views
2.9k
Activity
Apr ’22
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)")} } } }
Replies
1
Boosts
3
Views
2.2k
Activity
Oct ’23
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()
Replies
0
Boosts
1
Views
777
Activity
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()   } }
Replies
5
Boosts
0
Views
4.9k
Activity
Mar ’24
Why does SwiftUI sidebar not update when ObservedObject changes?
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)   } }
Replies
1
Boosts
0
Views
1k
Activity
Nov ’22
How to use network sockets with async/await?
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).
Replies
9
Boosts
0
Views
3.8k
Activity
Jul ’24
How to access parent in List View with children?
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) } } }
Replies
2
Boosts
0
Views
1.9k
Activity
Nov ’22
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() } }
Replies
3
Boosts
0
Views
1.2k
Activity
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.
Replies
6
Boosts
0
Views
3.7k
Activity
Dec ’22