Post

Replies

Boosts

Views

Activity

Can corrupt Xcode project explain broken intellisense?
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?
1
0
613
Jun ’23
Issues using git in XCode
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.
2
0
1.6k
Aug ’23
How to get SwiftUI views to move, not fade when animating change
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() }```
0
0
483
Mar ’24
SwiftUI TextField corrupts selection when inserting utf16
The example code below shows what I am trying to achieve: When the user types a '*', it should be replaced with a '×'. It looks like it works, but the cursor position is corrupted, even though it looks OK, and the diagnostics that is printed below shows a valid index. If you type "12*34" you get "12×43" because the cursor is inserting before the shown cursor instead of after. How can I fix this? struct ContentView: View { @State private var input: String = "" @State private var selection: TextSelection? = nil var body: some View { VStack { TextField("Type 12*34", text: $input, selection: $selection) .onKeyPress(action: {keyPress in handleKeyPress(keyPress) }) Text("Selection: \(selectionAsString())") }.padding() } func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result { if (keyPress.key.character == "*") { insertAtCursor(text: "×") moveCursor(offset: 1) return KeyPress.Result.handled } return KeyPress.Result.ignored } func moveCursor(offset: Int) { guard let selection else { return } if case let .selection(range) = selection.indices { print("Moving cursor from \(range.lowerBound)") let newIndex = input.index(range.lowerBound, offsetBy: offset, limitedBy: input.endIndex)! let newSelection : TextSelection.Indices = .selection(newIndex..<newIndex) if case let .selection(range) = newSelection { print("Moved to \(range.lowerBound)") } self.selection!.indices = newSelection } } func insertAtCursor(text: String) { guard let selection else { return } if case let .selection(range) = selection.indices { input.insert(contentsOf: text, at: range.lowerBound) } } func selectionAsString() -> String { guard let selection else { return "None" } switch selection.indices { case .selection(let range): if (range.lowerBound == range.upperBound) { return ("No selection, cursor at \(range.lowerBound)") } let lower = range.lowerBound.utf16Offset(in: input) let upper = range.upperBound.utf16Offset(in: input) return "\(lower) - \(upper)" case .multiSelection(let rangeSet): return "Multi selection \(rangeSet)" @unknown default: fatalError("Unknown selection") } } }
Topic: UI Frameworks SubTopic: SwiftUI
7
0
154
Sep ’25
How to rotate views in-place when orientation changes?
I would like to keep my layout the same, and only rotate views in-place when the screen orientation changes.Below is a simple example of what I am trying to acieve. It shows to TestViews horizontally when in portrait mode, and vertically when in landscape mode.I've made sure that the views themselve does not get re-created in the hope that it would only animate the difference in layout between portrait and landscape, but it makes the views very small, and then animate them in from the corner of the screen.What I am trying to acieve, is for each view to effectively rotate by 90 degrees when the orientation changes. Is it possible in swiftUI?[In my example below, I've hacked my AppDelegate to be my model to get rotation notifications from a publisher in it. This needs to be added for the example to work.]struct TestView: View { var text: String var body: some View { ZStack { RoundedRectangle(cornerRadius: 25.0, style: .continuous) .foregroundColor(Color(red: 0.2, green: 0.2, blue: 0.2)) Text(verbatim: text) .font(.system(size: 95)) .foregroundColor(.white) }.aspectRatio(1.0, contentMode: .fit) } } struct ContentView: View { @EnvironmentObject var model : AppDelegate private let testViews: [TestView] = (0...1).map { TestView(text: "\($0)") } var body: some View { ZStack { if !model.isPotrait { HStack { VStack { testViews[0] testViews[1] } } } else { VStack { HStack { testViews[0] testViews[1] } } } }.padding() } }
5
0
5.7k
Mar ’21
How to override Edit>Copy when first responder cannot copy
I have a program where I need to handle Edit>Copy when the first responder cannot. I've added the following to my AppDelegate: @IBAction @objc func copy(_ sender: Any?) {     // My code here...   } But Edit>Copy is greyed out on the menu unless a TextField has focus and it has text selected. How do I get my copy function called when the text field has focus but does not have text selected (or any other case where the current view with focus cannot handle copy)?
3
0
1.3k
Feb ’21
How do I implement a _global_ copy command for my app?
I would like to implement a global copy command for my app. The code below is an attempt at achieving this but does not work. struct ContentView: View {   @State private var name = ""      var body: some View {     VStack {       Text("Hallo \(name)")       TextField("Please enter your name", text: $name)     }     .onCopyCommand(perform: {       print("You got to onCopy")       var items = [NSItemProvider]()       let stringData = "Hallo \(name)".data(using: .utf8)!       items.append(NSItemProvider(item: stringData as NSData, typeIdentifier: kUTTypePlainText as String))       return items     })   } } When the user selects something in the TextField, then using the copy menu should copy that text to the clipboard but when it has nothing selected, then I want to copy "Hallo" and the name to the clipboard. As you can see, I tried using the onCopyCommand but Copy is always grayed out. Any ideas on how I can enable Copy on the menu, and handle it when the TextField does not have anything selected?
1
0
600
Feb ’21
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.6k
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.8k
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);   }
3
0
2.9k
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
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
985
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.8k
Nov ’22