The question is: how to focus on the TextEditor
when the app launches.
I have seen several questions and possible answers about focus on SwiftUI views and elements, but nothing that I've tried worked so far. I also know that on the next version of Swift, supporting macOS Monterrey, focusing will be handled differently, however I am still stuck with an application for macOS Big Sur.
Essentially I have application with the typical three column view.
The left-most view is a list
set as:
.listStyle(SidebarListStyle())
The middle one is another list
with a list of the filenames I want to load, and the third view, the right most, is a TextEditor
which shows the contents of the file loaded.
When the application launches the first item in the middle view gets automatically selected, and the contents of the file are loaded into the TextEditor
. However, the focus is nowhere. I have to manually set the focus on the text editor with my mouse.
I have tried with .focusable()
and tried creating other controls and set focus.
But, how do I set the focus to be on the TextEditor
when the app launches?
Thanks!
Edit - minimal reproducible example code as requested:
import SwiftUI
struct Mail: Identifiable, Hashable {
let id = UUID()
let date: Date
let subject: String
let body: String
var isFavorited = false
}
final class MailStore: ObservableObject {
@Published var allMails: [String: [Mail]] = [
"Inbox": [ .init(date: Date(), subject: "Subject1", body: "Very long body...") ],
"Sent": [ .init(date: Date(), subject: "Subject2", body: "Very long body...") ],
]
}
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct Sidebar: View {
@ObservedObject var store: MailStore
@Binding var selectedFolder: String?
@Binding var selectedMail: Mail?
var body: some View {
List {
ForEach(Array(store.allMails.keys), id: \.self) { folder in
NavigationLink(
destination: FolderView(
title: folder,
mails: store.allMails[folder, default: []],
selectedMail: $selectedMail
),
tag: folder,
selection: $selectedFolder
) {
Text(folder).font(.headline)
}
}
}.listStyle(SidebarListStyle())
}
}
struct FolderView: View {
let title: String
let mails: [Mail]
@Binding var selectedMail: Mail?
var body: some View {
List {
ForEach(mails) { mail in
NavigationLink(
destination: MailView(mail: mail),
tag: mail,
selection: $selectedMail
) {
VStack(alignment: .leading) {
Text(mail.subject)
Text(mail.date, style: .date)
}
}
}
}.navigationTitle(title)
}
}
struct MailView: View {
let mail: Mail
@State private var fullText: String = "This is some editable text..."
var body: some View {
VStack(alignment: .leading) {
TextEditor(text: $fullText)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
EDIT II
So, based on this, I need to hack a lot of code to make the TexEditor be focused. I guess it's not possible as of Big Sur, maybe for the next version of the OS, I can use focused.