Post not yet marked as solved
Can I open two separate Xcode windows with the same project ?
I have multiple monitors, so would love to be able use them to view different files of the same project.
Is there a way?
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)
}
}
}
Post not yet marked as solved
So like the title says, when I start up Xcode the preview won;t work till I run a debug session using the simulator.
Sometimes the debug session is unable to start the simulator, which I can start manually then run a debug session.
Once all the above is done, preview works.
Any idea what is causing this behavior?
Post not yet marked as solved
Is there any app out there that lets you browse through a CoreData database? When I first started to learn Swift, an app called Liya seemed to work. But alas, no longer.
it would just make it easier if there was anything out there that let you browse the data directly.
Thanks
Post not yet marked as solved
Would like to be able to bring up the iOS keyboard in a SwiftUI view without having to use a TextField? The goal would be to capture each keyup, or keydown, using .onKeyPress
While I thought I could create a TextField not visible to the user, was hoping there was a cleaner way.
Post not yet marked as solved
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()
}
Post not yet marked as solved
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 = " "
}
)
}
}
Using Xcode 15.0.1
The playground, for the code below, has been in "Launching ok" for over two minutes. Anything that I should look into? A little mind boggling actually.
import UIKit
var msg = "Hello World"
print ("\(msg)")
Post not yet marked as solved
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?
Post not yet marked as solved
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
It's a small thing, but every time I open my current Xcode project the default iOS device to run my app on is my phone. Is there a way to change it to one of the simulators? i.e. iPhone Pro 11?
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)
}
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
}
}
Post not yet marked as solved
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
}
}
}
Post not yet marked as solved
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