TextField onCommit is never called - swift

I have been working with SwiftUI for a week now, and as everyone, I am struggling to identify if something that doesn't work is either a bug or a misunderstanding on my part.
I am using the TextField view but the onCommit closure is never executed. The onEditingChanged works fine. It gets called with true when the text field gains focus, and it gets called with false when it looses it.
The onCommit closure, however, will never execute. According to the little documentation that is available in the code:
onCommit: The action to perform when the user performs an action
(usually the return key) while the TextField has focus.
This is the code:
TextField($value,
placeholder: Text(placeholder),
onEditingChanged: { edit in
print("edit = \(edit)")
},
onCommit: {
print("COMITTED!")
}).textFieldStyle(.roundedBorder).padding(.horizontal, 20)
Ideally, I would like to move the focus from the text field receiving the RETURN key and put the focus on the following field. It's easy with UITextField and the resignFirstResponder() and becomeFirstResponder().
I already managed to use the UIViewRepresentable to embed an old UITextField, but that's not the point of this post. I would really hope to make it work in pure SwiftUI code.
If I can ever get the onCommit to work, what should I put there to achieve my goal?
Update: It seems the problem is only present with iOS, not macOS where it seems to work fine.
Update 2: This is a video of the result of running the suggested code on my machine. I did file a bug with Apple... we'll see.

Your code should work fine, as it does on Xcode 11.0 beta 1. However, I can confirm this does not currently work as expected on beta 2. I filled a bug report to Apple for this issue.
Update: This issue was fixed with Xcode 11 beta 3.

Try it in the real simulator.
Keep some notes in mind:
Unfortunately debugger is not working with live preview
Console is not connected to the live preview, so print() result doesn't show up
You can change your code a bit and build a simple log console to see the result if you want to test it in preview mode:
Like this:
struct ContentView : View {
#State private var log: String = "Logs: "
#State var value: String = ""
var body: some View {
VStack() {
// Logger
Text(log)
.lineLimit(0)
.padding()
//
Spacer()
TextField($value,
placeholder: Text("placeholder"),
onEditingChanged: { edit in
self.log.append("\n edit = \(edit)")
},
onCommit: {
self.log.append("\n COMITTED!")
}).textFieldStyle(.roundedBorder).padding(.horizontal, 20)
Spacer()
}
}
}
Live preview has a bug that cause it to not work properly with keyboard and it has an epic delay (mine was about 15 minutes) to show the onscreen keyboard. So if you realy want to see the result in live preview, you should be very patient and wait for the keyboard:
Use simulator or real device to test what you want. Video: Xcode11-Beta1

Related

Set a background color for a view using .background()

I'm trying to follow Apple's introductory tutorial to SwiftUI.
In Section 3 Step 5 of the lesson, I get to the point where I have the following code:
import SwiftUI
struct CardView: View {
let scrum: DailyScrum
var body: some View {
Text(scrum.title) // returns the word "Design"
.font(.headline)
}
}
struct CardView_Previews: PreviewProvider {
static var scrum = DailyScrum.sampleData[0]
static var previews: some View {
CardView(scrum: scrum)
.background(scrum.theme.mainColor) // returns Color("yellow")
.previewLayout(.fixed(width: 400, height: 60))
}
}
According to the preview provided by the website, I should be getting the word "Design" with a yellow background, however, the yellow background doesn't show.
I tried changing the parameter to Color.yellow and it worked.
My question is, is there a difference between .background(Color("yellow")
and .background(Color.yellow), and if so why does apple's tutorial use the first one?
Yes. SwiftUI is relatively new technology, and is rapidly changing. Some changes was introduced into iOS 16 changing the .background view modifier... if you change your target to iOS 13 or iOS 14 .background(Color.yellow) should work. As a rule of thumb assume that the Apple's website docs and examples will always be a little bit old. So to use those websites they recommend that you download the example code, this code should be already set to older targets. But if you create a brand new project of your own and try to follow bit by bit some strange behavior could occur. The best documentation is the one embedded into the Xcode itself. Or, use the website for beginner learning using their example code.

SwiftUI: DatePicker can't be put in a VStack in Form

See this simple example. Putting DatePicker in VStack has weird layout issue and causes all the content in VStack to not show up (I'm using XCode 13.2 + iOS15.2).
struct ContentView: View {
#State var date: Date = Date()
var body: some View {
Form {
VStack {
DatePicker("Date", selection: $date)
Text("date: \(date)")
}
}
}
}
Replacing the DatePicker with other views (e.g. TextField) works fine. Removing the VStack also works fine. However, I need to have the VStack to make subviews inside it to show up in a single cell.
I googled but wasn't able to find any discussion about this issue. I tried to wrap DatePicker in HStack or ZStack but neither worked. Does anyone know how to work around this issue? Thanks.
A big thank to #Yrb, whose suggestion helps me to find the root cause of the issue.
TL;DR It's a simulator issue. Resetting the simulated device resolved the issue.
More details: I first noticed the issue when I tested my app on the simulator. I thought it was a bug with iOS, especially after I was able to reproduce the issue with the above code in a fresh project. Since #Yrb wasn't able to reproduce the issue, I was about to upgrade my system. However, his suggestion reminded me to try it again on other simulator (I usually use iPhone SE2). It was surprising that other devices didn't have the issue. What's more, while I could reproduce the issue consistently on iPhone SE2 simulator, the preview in XCode just worked fine. So I reset the iPhone SE2 simulator and restarted it (BTW, just restarting it didn't work), the code worked fine!
It's still a mystery what exactly happened in the simulator. But I'm glad to know it's neither my code issue nor an iOS issue.
It took me more than half a day to investigate the issue :( Lessons learned when running into similar weird issue in future: 1) reset simulator 2) try it on physical device also.

My CPU Usgage is constant 100% (Xcode, using SwiftUI)

My SwiftUI App is extremly lagging and I have no Idea why. Even if I only compile this code, my CPU Power goes up to 100%, even if I dont touch anything:
#main
struct Order_Corner_V8App: App {
var body: some Scene {
return WindowGroup {
TabView{
Text("").tabItem {
Text("click")
}
Text("").tabItem {
Text("click")
}
}
}
}
}
I need the TabView. I put my whole Files in an other new Project, the same thing happend again. Maybe its usefull to know that im working with Firebase.
I'm targeting iOS.
I've already watched to my App in 'Instruments', it only says that the problem is my main View.
Please help me.
Here is some image that shows my CPU Data
Thanks, Boothosh
Okay I got the solution: I tried the App on an other phone and everything works fine. I think this is an mistake of my phone, but I don't know what I can do against that.
Thanks, Boothosh
In my case, I found Xcode source control caused the problem
To fix this problem Xcode -> Preferences -> Source Control uncheck Enable Source control. Then restart Xcode, everything will be fine

context menu, strange constraint warning in console swiftUI

I have create a simple list in swiftUI in order to try the context menu
var body: some View {
List {
ForEach(self.dm.storage) { airportData in
Button(action: {
}) {
ZStack{
Text("Hello list")
}.contextMenu {
Text("Hello")
}
}
}
}
}
but when I run the code on the simulator I get this warning from swiftUI.
any reason why, how can I solve this issue?
thanks for the help
It's a SwiftUI Bug you don't have to worry about. Similar warnings appear if you use a Toogle for example.
This doesn't affect your App and can be ignored (also its annoying to see warnings in the console).
This is fixed as of Xcode beta 12.0. This was confirmed by a response today, to my feedback radar sent on April 1st. I then tested it and it all works perfectly now.
No more strange warnings!

Unable to see preview and unable to see the main window of my app (when running) while using swift ui for macOS developement

So I created a macOS cocoa project called "test" using swift ui in Xcode 11 beta and got problems at the very beginning.
Sorry in advance if my question is dumb.
The first problem is that the automatic preview says it is in pause. If I click resume, I got an error.
So I tried to run the code Xcode generated (I changed nothing in the code.) and it build successfully. When I tried to run the code freshly build, I come across the following error: EXC_BAD_INSTRUCTION
The line highlighted in red is the .frame line in the following piece of code:
import SwiftUI
struct ContentView : View {
var body: some View {
Text("Hello World")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
I'm on macOS Catalina Public Beta 1 so this is not a problem with the version of the system....
So, did I miss something? The tutorials I found online (I mostly looked on Youtube and Apple Dev websites) either show examples for iOS or show examples that are not starting from scratch ( For example on Apple websites, when they are demo-ing codes for macOS apps ).
Thanks in advance
EDIT
I'm adding this picture, it might help:
Actual screen when the app is running with the info of the threads section
Final answer:
Just needed an update Xcode to beta 2 :) .