Post

Replies

Boosts

Views

Activity

Can a button call a new view without using NavigationStack/Link/View?
Is it possible to switch to a new View without using NavigationStack or NavigationLink or NavigationView? I know I can do it with a Bool, which either shows the second view, or the first, and then toggles the Bool. But can't I do something like this? Which obviously doesn't work. struct BasicButton: View { var buttonLabel = "Create User" var body: some View { Button { CreateUser() //another SwiftUI view, not a function } label: { Text(buttonLabel) } } }
3
0
162
3w
Is there a trick to viewing an EnvironmentObject in Xcode debugger? They currently show up as invalid Expression.
I am trying to watch an @EnvironmentObject in the Xcode debugger and it comes up as an Invalid Expression in the View pane. If I want to view it, I need to declare it as a local variable and then assign it the value of the passed in @EnvironmentObject. While not impossible, it's a lot of work. Or maybe I am doing something incorrectly and this is a symptom of that? Would like to resolve this. encl: Example code & Screenshot, where choice is the passed/unviewable EnviornmentObject and ch is the local variable I use to view it in the debugger Project "TestingApp" File: TestingApp import SwiftUI @main struct TestingApp: App { @StateObject private var choice = Choices() var body: some Scene { WindowGroup { ContentView() .environmentObject(choice) } } } File: Choices import Foundation @MainActor class Choices: ObservableObject { @Published var aChoice = 1 @Published var bChoice = 2 } File: ContentView import SwiftUI struct ContentView: View { @EnvironmentObject private var choice: Choices var body: some View { VStack { let ch = choice Text("\(choice.aChoice)") .font(.largeTitle) .padding(.bottom) Text("2") .font(.largeTitle) } .padding() } } #Preview { ContentView() }
0
0
239
Mar ’24
Where can I find a tutorial on using GeometryReader within a View's background (closure) modifier?
Someone showed me the code below, when I was trying to figure out how to detect which views were being intercepted by one continuous DragGesture. It works, but I would like to find a tutorial whre I can learn what's going on here. From what I can tell, the background modifier is a closure, that calls a function which has a GeometryReader which returns a view. I've Googled .background as a closure in swiftui and still can't find any form of tutorial that discuss what is going on here. Not looking for the answers, looking to learn. Thank you struct ContentView: View { @State private var dragLocation = CGPoint.zero @State private var dragInfo = " " private func dragDetector(for name: String) -> some View { GeometryReader { proxy in let frame = proxy.frame(in: .global) let isDragLocationInsideFrame = frame.contains(dragLocation) let isDragLocationInsideCircle = isDragLocationInsideFrame && Circle().path(in: frame).contains(dragLocation) Color.clear .onChange(of: isDragLocationInsideCircle) { oldVal, newVal in if dragLocation != .zero { dragInfo = "\(newVal ? "entering" : "leaving") \(name)..." } } } } var body: some View { ZStack { Color(white: 0.2) VStack(spacing: 50) { Text(dragInfo) .foregroundStyle(.white) HStack { Circle() .fill(.red) .frame(width: 100, height: 100) .background { dragDetector(for: "red") } Circle() .fill(.white) .frame(width: 100, height: 100) .background { dragDetector(for: "white") } Circle() .fill(.blue) .frame(width: 100, height: 100) .background { dragDetector(for: "blue") } } } } .gesture( DragGesture(coordinateSpace: .global) .onChanged { val in dragLocation = val.location } .onEnded { val in dragLocation = .zero dragInfo = " " } ) } }
0
0
187
Jan ’24
How can I dismiss keyboard on TextField losing focus?
Am trying to figure out how to dismiss the iOS keyboard if my TextFields do not have focus. Obviously when clicking a button I can call a dismiss keyboard function. But what I wanted to learn was how to dismiss the keyboard of if the user hits return OR clicks off of the TextFields. Before I could figure out the "user hit return part" I got stuck at the user being able to click away from the TextFields. While I can add a onTapGesture to the text fields, I wonder if I can do something like detecting a tapGesture to the entire screen, so that if the user taps on any blank space I could call the dismiss keyboard function. import SwiftUI struct ContentView: View { @State var textField1 = "" @State var textField2 = "" @State var hasFocus = "No text field has focus" @FocusState var leftTyping : Bool @FocusState var rightTyping : Bool var body: some View { VStack { Text(hasFocus) .font(.largeTitle) HStack { TextField("left" , text: $textField1) .focused($leftTyping) .onChange(of: leftTyping) { if leftTyping == false, rightTyping == false { hideKeyboard() hasFocus = "No text field has focus" } else if leftTyping { hasFocus = "focus on left field" } } TextField("right", text: $textField2) .focused($rightTyping) .onChange(of: rightTyping) { if leftTyping == false, rightTyping == false { hideKeyboard() hasFocus = "No text field has focus" } else if rightTyping { hasFocus = "focus on right field" } } } Button ("steal focus"){ hideKeyboard() hasFocus = "No text field has focus" } .buttonStyle(.borderedProminent) .tint(.brown) .font(.largeTitle) .padding(10) .foregroundStyle(.white) } .padding() } func hideKeyboard() { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } #Preview { ContentView() } Is there a way to do this?
0
0
386
Dec ’23
Can I install Xcode on an external HD?
I hope this isn't too off-topic, but I'm in a bind My HD is so full that I can't download any new iOS' in Xcode. Actually, there's a lot I can't do. According to the storage part of System Details, Developer is over 100 GB. I have a huge external HD and would like to completely remove and clean Xcode, and the reinstall it on the external HD. 1 - Is this allowed? Some people say that all apps must be installed in the Applications folder. Checking the web I get both answers. 2 - If it is allowed, is there a way to properly clean out? Because every website I found that describes this procedure is touting their own cleanup app. Thank you
1
0
418
Nov ’23
Is there an .onAppear equivalent that works on individual items in a view, and also gets called on redraws?
Within my SwiftUI view I have multiple view items, buttons, text, etc. Within the view, the user selects a ticket, and then clicks a button to upload it. The app then sends the ticket to my server, where the server takes time to import the ticket. So my SwiftUI app needs to make repeated URL calls depending on how far the server has gotten with the ticket. I thought the code below would work. I update the text to show at what percent the server is at. However, it only works once. I guess I thought that onAppear would work with every refresh since it's in a switch statement. If I'm reading my debugger correctly, SwiftUI recalls which switch statement was called last and therefore it views my code below as a refresh rather than a fresh creation. So is there a modifier that would get fired repeatedly on every view refresh? Or do I have to do all my multiple URL calls from outside the SwiftUI view? Something like onInitialize but for child views (buttons, text, etc.) within the main view? switch myNewURL.stage { case .makeTicket: Text(myNewURL.statusMsg) .padding(.all, 30) case .importing: Text(myNewURL.statusMsg) .onAppear{ Task { try! await Task.sleep(nanoseconds: 7000000000) print ("stage two") let request = xFile.makeGetReq(xUser: xUser, script: "getTicketStat.pl") var result = await myNewURL.asyncCall(request: request, xFile: xFile) } } .padding(.all, 30) case .uploadOriginal: Text(myNewURL.statusMsg) .padding(.all, 30) case .JSONerr: Text(myNewURL.statusMsg) .padding(.all, 30) }
1
0
500
Jul ’23
Why must I wrap a call to call to an async/await method in a Task?
Trying to to convert my old URL functionality to SwiftUI with async/await. While the skeleton below works, am puzzled as to why I must place my call to the method within a Task? When I don't use Task I get the error: Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type From the examples I've seen, this wasn't necessary. So I either I've misunderstood something, or I am doing this incorrectly, and am looking for little but of guidance. Thank you Within my SwiftUI view: Button { Task { let request = xFile.makePostRequest(xUser: xUser, script: "requestTicket.pl") var result = await myNewURL.asyncCall(request: request) print("\(result)") } } From a separate class: class MyNewURL: NSObject, ObservableObject { func asyncCall(request: URLRequest) async -> Int { do { let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { print("error") return -1 } if httpResponse.statusCode == 200 { ... } } catch { return -2 } return 0 } }
1
0
1.6k
Jul ’23
How can I keep a class declaration within SwiftUI view persistent through any of the view's updates?
I have a class, MyURL, from a UIKit app that I wrote that handles all my URL needs, uploads, downloads, GETS, POSTS, etc. I would like to use that class from within a SwiftUI view now. So the SwiftUI view that creates calls MyURL methods. And I would pass binding vars that would cause my SwiftUI view to update things such as statuses : percentage done, etc. My issue is, how can I properly declare that class, myURL, from within the SwiftUI view, so that it doesn't get redeclared every time the view updates. Should I declare the MyURL class in a view above it and pass it into the view that calls the MyUrl class? Would just like to do it the proper way. I wish I was better with terminology. Thank you struct ContentView: View { **var myURL = MyURL()** @State var proceed = false var body: some View { Button { myURL.pressed(proceed: $proceed) } label: { Text(proceed ? "pressed" : "not pressed") } } } class MyURL: NSObject, URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate, URLSessionDownloadDelegate{ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { } func pressed(proceed: Binding<Bool>) { print("\(proceed)") proceed.wrappedValue.toggle() } // Error received func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let err = error { DispatchQueue.main.async { [self] in //code } } } // Response received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { completionHandler(URLSession.ResponseDisposition.allow) if let httpResponse = response as? HTTPURLResponse { xFile?.httpResponse = httpResponse.statusCode DispatchQueue.main.async { [self] in if httpResponse.statusCode != 200 { //code } } } } // Data received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if xFile?.httpResponse == 200 { DispatchQueue.main.async { [self] in //code } } //DispatchQueue.main.async } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let num : Float = Float(totalBytesWritten * 100) let den : Float = Float(totalBytesExpectedToWrite * 100) let percentDownloaded : Int = Int(num/den * 100) DispatchQueue.main.async { [self] in //code } } }
0
0
294
Jun ’23
Am lost using URLSessionDelegate within SwiftUI
Trying to create an app in SwiftUI that uses HTTP for "gets", "posts", "forms", et al. I cannot assign URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate to a SwiftUI view. So my assumption is that I need to create a UIViewControllerRepresentable for a regular UIViewController and assign the delegates to that UIViewController I just need to know if this is the correct path to proceed with? Or is there some sort ion tie in that I cannot find using Google? Thank you
0
0
309
Jun ’23
Why do I get a "Publishing changes from within view updates is not allowed" when moving my @Bindings to @Published in an @ObservableObject?
Am going through a SwiftUI course, so the code is not my own. When I migrated my @Bindings into @Published items in an @ObservableObject I started getting the following error: Publishing changes from within view updates is not allowed, this will cause undefined behavior. The warning occurs in the ScannerView which is integrated with the main view, BarcodeScannerView. It occurs when an error occurs, and scannerView.alertItem is set to a value. However, it does not occur when I am setting the value of scannerView.scannedCode, and as far as I can tell, they both come from the sample place, and are the same actions. There are tons of posts like mine, but I have yet to find an answer. Any thoughts or comments would be very appreciated. BarcodeScannerView import SwiftUI struct BarcodeScannerView: View { @StateObject var viewModel = BarcodeScannerViewModel() var body: some View { NavigationStack { VStack { ScannerView(scannedCode: $viewModel.scannedCode, typeScanned: $viewModel.typeScanned, alertItem: $viewModel.alertItem) .frame(maxWidth: .infinity, maxHeight: 300) Spacer().frame(height: 60) BarcodeView(statusText: viewModel.typeScanned) TextView(statusText: viewModel.statusText, statusTextColor: viewModel.statusTextColor) } .navigationTitle("Barcode Scanner") .alert(item: $viewModel.alertItem) { alertItem in Alert(title: Text(alertItem.title), message: Text(alertItem.message), dismissButton: alertItem.dismissButton) } } } } BarcodeScannerViewModel import SwiftUI final class BarcodeScannerViewModel: ObservableObject { @Published var scannedCode = "" @Published var typeScanned = "Scanned Barcode" @Published var alertItem: AlertItem? var statusText: String { return scannedCode.isEmpty ? "Not Yet scanned" : scannedCode } var statusTextColor: Color { scannedCode.isEmpty ? .red : .green } } ScannerView import SwiftUI struct ScannerView: UIViewControllerRepresentable { typealias UIViewControllerType = ScannerVC @Binding var scannedCode : String @Binding var typeScanned : String @Binding var alertItem: AlertItem? func makeCoordinator() -> Coordinator { Coordinator(scannerView: self) } func makeUIViewController(context: Context) -> ScannerVC { ScannerVC(scannerDelegate: context.coordinator) } func updateUIViewController(_ uiViewController: ScannerVC, context: Context) { } final class Coordinator: NSObject, ScannerVCDelegate { private let scannerView: ScannerView init(scannerView: ScannerView) { self.scannerView = scannerView } func didFind(barcode: String, typeScanned: String) { scannerView.scannedCode = barcode scannerView.typeScanned = typeScanned print (barcode) } func didSurface(error: CameraError) { switch error { case .invalidDeviceinput: scannerView.alertItem = AlertContext.invalidDeviceInput case .invalidScannedValue: scannerView.alertItem = AlertContext.invalidScannedValue case .invalidPreviewLayer: scannerView.alertItem = AlertContext.invalidPreviewLayer case .invalidStringObject: scannerView.alertItem = AlertContext.invalidStringObject } } } }
4
0
2.5k
Mar ’23