Setting TextField /TextEditor as the first responder upon appearing SwifUI - swift

I've got a SwiftUI TextEditor that appears once a button is pressed. What I can't figure out is, how to make the TextEditor the first responder when it appears.
What I've tried is adding a .focused modifier to the TextEditor and then setting the focused Bool value to true inside .onAppear. But still the keyboard only shows up when its pressed.
import SwiftUI
struct ContentView: View {
#State var showTextField : Bool = false
#State private var currentEditText : String = "Some text"
#FocusState private var editTextFieldFocus: Bool
var body: some View {
VStack {
Button {
showTextField.toggle()
} label: {
Text("Show Text Field")
}
Text("Hello, world!")
.padding()
if showTextField{
TextEditor(text: $currentEditText)
.focused($editTextFieldFocus)
.onAppear {
editTextFieldFocus = true
}
}
}
}
}

Related

SwiftUI keyboard-shortcut without modifier doesn't work in popover

In a View with a textfield I have a popover, activated by a button.
In that popover I want to listen to a keyboardShortcut without modifiers.
These keypresses arrive in the textfild of the parent view instead of the popover.
What can I do, to react on these in the popover?
struct ContentView: View {
#State var showPopOver = false
#State var text = ""
var body: some View {
VStack{
TextField("enter text here", text: $text)
Button("show popover"){ showPopOver = true }
.popover(isPresented: $showPopOver) {PopOverView(text: $text)} }
.keyboardShortcut("p")
.padding()
}
}
struct PopOverView: View {
#Environment(\.dismiss) var dismiss
#Binding var text: String
var body: some View {
VStack{
Text("my Popover")
Button("set Tom"){
text = "Tom"
dismiss()
}
.keyboardShortcut("t",modifiers: [])
//.keyboardShortcut("t") // like this it works
Button("set Frank"){
text = "Frank"
dismiss()
}
.keyboardShortcut("f",modifiers: [])
}
.padding()
}
}
KeyboardShortcuts with a modifier in the popover do work (commented out).

Pin TextField to Keyboard in SwiftUI

Is it possible to pin a textfield to the top of the keyboard in SwiftUI? Pretty much identical to the messaging app on iOS where it it is at the bottom of the screen on appear, but moves with the keyboard when you click it, but with SwiftUI, I've looked around and not been able to find anything.
You can achieve this with a toolbar modifier and an toolbaritemgroup with .keyboard placement.
struct ToolBarTest: View {
#State private var text: String = ""
#FocusState private var focus: Bool
#FocusState private var focusToolbar: Bool
var body: some View {
ZStack {
VStack{
Spacer()
TextField("toolbar", text: $text)
.textFieldStyle(.roundedBorder)
.opacity(focus || focusToolbar ? 0 : 1)
.focused($focus)
}
.toolbar {
ToolbarItemGroup(placement: .keyboard){
TextField("toolbar", text: $text)
.textFieldStyle(.roundedBorder)
.focused($focusToolbar)
}
}
.onChange(of: focus) {
if $0{
focusToolbar = true
}
}
}
}
}

TextField's .focused modifier not working when "out of view" SwiftUI

I'm working with a SwiftUI List with a TextEditor at the bottom of the List. The TextEditor becomes active or "Focused" when a button is pressed.
To achieve this, I have added a .focused modifier to the TextEditor. When the List is scrolled to the bottom and the TextEditor is visible this works as expected and shows the keyboard when the button is pressed.
But the problem is that when the List is scrolled to the top and the TextEditor is not visible on the screen the TextField doesn't seem to get focused.
import SwiftUI
struct ContentView: View {
var array = Array(0...20)
#State private var newItemText : String = ""
#FocusState var focused: Bool
var body: some View {
VStack{
List{
ForEach(array, id: \.self) {
Text("\($0)")
}
TextEditor(text: $newItemText)
.focused($focused)
}
Button {
focused = true
} label: {
Text("Add Item")
}
}
}
}
You have to set the field in a DispatchQueue.
import SwiftUI
struct ContentView: View {
var array = Array(0...20)
#State private var newItemText : String = ""
#FocusState var focusedField: Bool
var body: some View {
VStack {
ScrollViewReader { scrollView in
List {
ForEach(array, id: \.self) {
Text("\($0)")
}
TextField("", text: self.$newItemText)
.id("TextEditor")
.focused($focusedField)
}
Button(action: {
scrollView.scrollTo("TextEditor")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.focusedField = true
}
}) {
Text("Add Item")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Hope this solves your problem!

How can I remove TextField focus when tapping a different view using .focused()?

I'm trying to use iOS15's .focused() modifier to enable the user to tap anywhere outside of a text field to remove focus. I am going off of the example provided in: https://www.youtube.com/watch?v=GqXVFXnLVH4. Below is my non-working attempt:
enum Field {
case textField
case notTextField
}
struct ContentView: View {
#State var textInput = ""
#FocusState var focusState:Field?
var body: some View {
VStack {
TextField("Enter some text...", text: $textInput)
.focused($focusState, equals: .textField)
Rectangle()
.focused($focusState, equals: .notTextField)
.onTapGesture {
state = .notTextField
}
}
}
}
I found the solution was not to focus another element, but to switch the textfield's focus to false:
#State var textInput = ""
#FocusState var textFieldIsFocused: Bool
var body: some View {
VStack {
TextField("Enter some text...", text: $textInput)
.focused($textFieldIsFocused)
Rectangle()
.onTapGesture {
textFieldIsFocused = false
}
}
}

TextField with animation crashes app and looses focus

Minimal reproducible example:
In SceneDelegate.swift:
let contentView = Container()
In ContentView.swift:
struct SwiftUIView: View {
#State var text: String = ""
var body: some View {
VStack {
CustomTextFieldView(text: $text)
}
}
}
struct Container: View {
#State var bool: Bool = false
#State var text: String = ""
var body: some View {
Button(action: {
self.bool.toggle()
}) {
Text("Sheet!")
}
.sheet(isPresented: $bool) {
SwiftUIView()
}
}
}
In CustomTextField.swift:
struct CustomTextFieldView: View {
#Binding var text: String
#State var editing: Bool = false
var body: some View {
Group {
if self.editing {
textField
.background(Color.red)
} else {
ZStack(alignment: .leading) {
textField
.background(Color.green)
Text("Placeholder")
}
}
}
.onTapGesture {
withAnimation {
self.editing = true
}
}
}
var textField: some View {
TextField("", text: $text)
}
Problem:
After running the above code and focusing the text field, the app crashes. Some things I noticed:
If I remove the withAnimation code, or the ZStack in CustomTextField file, the app doesn't crash, but the TextField looses focus.
If I remove the VStack in SwiftUIView, the app doesn't crash, but the TextField looses focus.
If I use a NavigationLink or present the TextField without a sheet, the app doesn't crash, but the TextField looses focus.
Questions:
Is this a problem in the current version of SwiftUI?
Is there a solution to this problem using SwiftUI? I want to stay out of
ViewRepresentables as much as possible.
How can I keep the focus of the TextField after the body is recalculated because of a change in state?
How can I keep the focus of the TextField after the body is
recalculated because of a change in state?
You have two of them. Two different TextField could not be in editing state at the same time.
The approach suggested by Asperi is the only possible.
The reason, why your code crash is not easy explain, but expected in current SwiftUI.
You have to understand, that Group is not a standard container, it just like a "block" on which you can apply some modifiers. Removing Group and using wraping body in ViewBuilder
struct CustomTextFieldView: View {
#Binding var text: String
#State var editing: Bool = false
#ViewBuilder
var body: some View {
if self.editing {
TextField("", text: $text)
.background(Color.red)
.onTapGesture {
self.editing.toggle()
}
} else {
ZStack(alignment: .leading) {
TextField("", text: $text)
.background(Color.green)
.onTapGesture {
self.editing.toggle()
}
}
}
}
}
the code will stop to crash, but there is other issue, the keyboard will dismiss immediately. That is due the tap gesture applied.
So, believe or not, you have to use ONE TextField ONLY.
struct CustomTextFieldView: View {
#Binding var text: String
#State var editing = false
var textField: some View {
TextField("", text: $text, onEditingChanged: { edit in
self.editing = edit
})
}
var body: some View {
textField.background(editing ? Color.green : Color.red)
}
}
Use this custom text field elsewhere in your code, as you want
Try the following for CustomTextFieldView (tested & works with Xcode 11.2 / iOS 13.2)
struct CustomTextFieldView: View {
#Binding var text: String
#State var editing: Bool = false
var body: some View {
TextField("", text: $text)
.background(self.editing ? Color.red : Color.green)
.onTapGesture {
withAnimation {
self.editing = true
}
}
}
}
How can I keep the focus of the TextField after the body is recalculated because of a change in state?
You don't loose focus, you just remove entire text field, so the solution is not replace text field, but modify its property, ie background. It's ok to put it into ZStack, but keep it one.