I am having a problem on a simple Form{}. Automatic Keyboard Avoidance is not working. Below is a small form with a TextEditor(). When run, the keyboard sits on top the input field, requiring the user to scroll the view so thay can enter a location. Remove the Form{} and Automatic Keyboard Avoidance works. Am I missing something I need to do in a Form{} to get this behavior?
import SwiftUI
struct ContentView: View {
#State private var stopLocation: String = ""
var body: some View {
Form {
let desc = "\n\n\n\n\n\n\n\n\n\n\n\nEnter Location"
Text(desc)
VStack {
TextEditor(text: $stopLocation)
}
}
}
}
Related
I want to use a List, #FocusState to track focus, and .onChanged(of: focus) to ensure the currently focused field is visible with ScrollViewReader. The problem is: when everything is setup together the List rebuilds constantly during scrolling making the scrolling not as smooth as it needs to be.
I found out that the List rebuilds on scrolling when I attach .onChanged(of: focus). The issue is gone if I replace List with ScrollView, but I like appearance of List, I need sections support, and I need editing capabilities (e.g. delete, move items), so I need to stick to List view.
I used Self._printChanges() in order to see what makes the body to rebuild itself when scrolling and the output was like:
ContentView: _focus changed.
ContentView: _focus changed.
ContentView: _focus changed.
ContentView: _focus changed.
...
And nothing was printed from the closure attached to .onChanged(of: focus). Below is the simplified example, the smoothness of scrolling is not a problem in this example, however, once the List content is more or less complex the smooth scrolling goes away and this is really due to .onChanged(of: focus) :(
Question: Are there any chances to listen for focus changes and not provoke the List to rebuild itself on scrolling?
struct ContentView: View {
enum Field: Hashable {
case fieldId(Int)
}
#FocusState var focus: Field?
#State var text: String = ""
var body: some View {
List {
let _ = Self._printChanges()
ForEach(0..<100) {
TextField("Enter the text for \($0)", text: $text)
.id(Field.fieldId($0))
.focused($focus, equals: .fieldId($0))
}
}
.onChange(of: focus) { _ in
print("Not printed unless focused manually")
}
}
}
if you add printChanges to the beginning of the body, you can monitor the views and see that they are being rendered by SwiftUI (all of them on each focus lost and focus gained)
...
var body: some View {
let _ = Self._printChanges() // <<< ADD THIS TO SEE RE-RENDER
...
so after allot of testing, it seams that the problem is with .onChange, once you add it SwiftUI will redraw all the Textfields,
the only BYPASS i found is to keep using the deprecated API as it works perfectly, and renders only the two textfields (the one that lost focus, and the one that gained the focus),
so the code should look this:
struct ContentView: View {
enum Field: Hashable {
case fieldId(Int)
}
// #FocusState var focus: Field? /// NO NEED
#State var text: String = ""
var body: some View {
List {
let _ = Self._printChanges()
ForEach(0..<100) {
TextField("Enter the text for \($0)", text: $text)
.id(Field.fieldId($0))
// .focused($focus, equals: .fieldId($0)) /// NO NEED
}
}
// .onChange(of: focus) { _ in /// NO NEED
// print("Not printed unless focused manually") /// NO NEED
// } /// NO NEED
.focusable(true, onFocusChange: { focusNewValue in
print("Only textfileds that lost/gained focus will print this")
})
}
}
I recommend to consider separation of list row content into standalone view and use something like focus "selection" approach. Having FocusState internal of each row prevents parent view from unneeded updates (something like pre-"set up" I assume).
Tested with Xcode 13.4 / iOS 15.5
struct ContentView: View {
enum Field: Hashable {
case fieldId(Int)
}
#State private var inFocus: Field?
var body: some View {
List {
let _ = Self._printChanges()
ForEach(0..<100, id: \.self) {
ExtractedView(i: $0, inFocus: $inFocus)
}
}
.onChange(of: inFocus) { _ in
print("Not printed unless focused manually")
}
}
struct ExtractedView: View {
let i: Int
#Binding var inFocus: Field?
#State private var text: String = ""
#FocusState private var focus: Bool // << internal !!
var body: some View {
TextField("Enter the text for \(i)", text: $text)
.focused($focus)
.id(Field.fieldId(i))
.onChange(of: focus) { _ in
inFocus = .fieldId(i) // << report selection outside
}
}
}
}
Why the presetsList does not appear? No errors were thrown though.
import SwiftUI
struct AddMessagePreset: View {
let presetsList = [
Preset(name: "preset text 1"),
Preset(name: "preset text 2"),
Preset(name: "preset text 3")
]
var body: some View {
List(presetsList) { singlePresetModel in
SinglePresetChild (presetModel: singlePresetModel)
}
}
}
import SwiftUI
struct Preset: Identifiable {
let id = UUID()
let name: String
}
struct SinglePresetChild: View {
var presetModel: Preset
var body: some View {
Text("Preset Name \(presetModel.name)")
}
}
UPDATE: To show a List inside another ScrollView (or List), you have to set a height on the inner list view:
struct Preview: View {
var body: some View {
ScrollView {
AddMessagePreset().frame(height: 200)
// more views ...
}
}
}
But let me advise against doing so. Having nested scroll areas can be very confusing for the user.
As discussed in the comments, your component code is fine. However, the way you integrate it into your app causes a problem. Apparently, nesting a List inside a ScrollView does not work properly (also see this thread).
List is already scrollable vertically, so you won't need the additional ScrollView:
struct Preview: View {
var body: some View {
VStack {
AddMessagePreset()
}
}
}
P.S.: If you only want to show AddMessagePreset and won't add another sibling view, you can remove the wrapping VStack; or even show AddMessagePreset as the main view, without any wrapper.
I am trying to create a TextField that spans across the entire window. Currently it only expands to fill the view on the horizontal axis. I'm aiming to achieve something similar to that seen in TextEdit.
Here is my code so far:
struct ContentView: View {
#State var contents: String = "Hello World\nThis is a test.";
var body: some View {
VStack() {
TextField("Notes", text: $contents)
.lineLimit(nil)
}
.frame(height: 600)
}
}
Application Screenshot
Is this possible in SwiftUI or will I need to revert to using legacy AppKit components?
I've found that wrapping an NSTextView is still be the best way to achieve something similar to that seen in TextEdit. So yes, at least now you will have to use legacy AppKit components in your SwiftUI code.
struct MultilineTextView: NSViewRepresentable {
typealias NSViewType = NSTextView
#Binding var text: String
func makeNSView(context: Self.Context) -> Self.NSViewType{
let view = NSTextView()
view.isEditable = true
view.isRulerVisible = true
return view
}
func updateNSView(_ nsView: Self.NSViewType, context: Self.Context) {
nsView.string = text
}
}
struct ContentView: View {
#State var contents: String = "Hello World\nThis is a test.";
var body: some View {
VStack() {
MultilineTextView(text: $contents)
}.background(Color.white)
}
}
It seems, that there is bug with TextField line limit, according to this answer and comments to it.
I believe in this thread you can find answer, how achieve what you want.
Just replying to this as nobody's given a decent answer yet besides wrapping UIKit.
TextEditor(text: $contents)
Is the better path as it WILL behave like you wish as compared to TextField(). It automatically takes care of scrolling and expanding to the View area allowed.
TextEditor WILL require you to be on at least iOS 14. If you're not on iOS 14 then wrapping the UIKit control is your best option.
The new SwiftUI is fantastic to play with... I'm trying to use Forms instead of Eureka. A couple of questions:
What is the best way to let the user enter a number? I used to do that with a UIPickerView, see image .
With SwiftUI I only found Textfield, as in the following code:
import SwiftUI
struct SettingsView : View {
#State var email = ""
#State var amount = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("Email")) {
TextField("Your email", text: $email)
.textFieldStyle(.roundedBorder)
}
Section(header: Text("Amount")) {
TextField("Amount", text: $amount)
.textFieldStyle(.roundedBorder)
}
.navigationBarTitle("Settings")
}
}
}
}
When you click in the field, the ABC keyboard comes up. The user can select '123' to get the number keyboard. But I would like to see a number pad instead.
Also, the keyboard blocks the view (if you have more fields); the view doesn't scroll up to make room for the keyboard.
Is it possible to get rid of the keyboard when the user clicks outside a TextField?
And is there a way to 'validate the entries'? For instance, the amount should be between 10 and 1.000?
I am creating a sign in page for my app and would like to present the home screen in a way that the user can not go back. In Swift UI how do I present it so the new view does not present in a card like style? I know this presenting style is now default for iOS 13.
This is what I already have.
import SwiftUI
struct Test : View {
var body: some View {
PresentationButton(Text("Click to show"), destination: Extra() )
}
}
I would like the view to present full screen.
Use a NavigationView with a NavigationButton and hide the destination view's navigation bar's back button.
For example:
struct ContentView : View {
let destinationView = Text("Destination")
.navigationBarItem(title: Text("Destination View"), titleDisplayMode: .automatic, hidesBackButton: true)
var body: some View {
NavigationView {
NavigationButton(destination: destinationView) {
Text("Tap Here")
}
}
}
}
You can also disable the destination view's navigation bar altogether by doing let destinationView = Text("Destination").navigationBarHidden(true).