How do I set or disable main menu keyboard shortcut programmatically in SwiftUI for a macOS app? - macos

Say, I want to add the following main menu item to my macOS app - Next:
#main
struct MyApp: App {
#ObservedObject var appState = DataViewModel.shared
var body: some Scene {
WindowGroup
{
ContentView()
}
.commands {
CommandGroup(replacing: .pasteboard) {
Button(action: {
appState.nextCurrentID()
}) { Text("Next")}
.keyboardShortcut("V", modifiers: [.command, .option, .shift])
}
}
}
}
But I want to do the following depending on two variables:
enable/disable that menu item's keyboard shortcut depending on appState.EnableShortcutKey
Set the shortcut key depending on appState.ShortcutKey
Set modifiers depending on appState.Modifiers
Where those state variables are declared as such:
#Published public var EnableShortcutKey : Bool = false
#Published public var ShortcutKey : String = "A"
#Published public var Modifiers : NSEvent.ModifierFlags = [.command, .shift]
How do I do that?

Like this:
#main
struct SO_mac_TestsApp: App {
#StateObject var menuOptions = MenuOptions()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(menuOptions)
}
.commands {
CommandGroup(replacing: .pasteboard) {
Button(action: {
print("appState.nextCurrentID()")
}) { Text("Next")}
.keyboardShortcut(menuOptions.shortcutKey, modifiers: menuOptions.modifiers)
.disabled(menuOptions.enableShortcutKey == false)
}
}
}
}
class MenuOptions: ObservableObject {
#Published public var enableShortcutKey : Bool = false
#Published public var shortcutKey : KeyEquivalent = "A"
#Published public var modifiers : EventModifiers = [.command, .shift]
}
truct ContentView: View {
#EnvironmentObject var menuOptions: MenuOptions
#State private var shortcut = ""
var body: some View {
Form {
Toggle("Enable Shortcut", isOn: $menuOptions.enableShortcutKey)
TextField("Shortcut", text: $shortcut)
.onSubmit {
menuOptions.shortcutKey = KeyEquivalent(shortcut.first ?? "V")
}
Divider()
Text("Modifiers:")
Toggle("command:", isOn: Binding(
get: { menuOptions.modifiers.contains(.command) },
set: { new,_ in
if new { menuOptions.modifiers.insert(.command)
} else { menuOptions.modifiers.subtract(.command) }
}
) )
Toggle("option:", isOn: Binding(
get: { menuOptions.modifiers.contains(.option) },
set: { new,_ in
if new { menuOptions.modifiers.insert(.option)
} else { menuOptions.modifiers.subtract(.option) }
}
) )
Toggle("shift:", isOn: Binding(
get: { menuOptions.modifiers.contains(.shift) },
set: { new,_ in
if new { menuOptions.modifiers.insert(.shift)
} else { menuOptions.modifiers.subtract(.shift) }
}
) )
Toggle("control:", isOn: Binding(
get: { menuOptions.modifiers.contains(.control) },
set: { new,_ in
if new { menuOptions.modifiers.insert(.control)
} else { menuOptions.modifiers.subtract(.control) }
}
) )
}
.padding()
.onAppear {
shortcut = String(menuOptions.shortcutKey.character)
}
}
}

Related

Swift if statement in modifier

So I have an basic Taskview:
TabView {
NavigationView {
TasksView()
}
.tabItem {
Image(systemName: "bookmark")
Text("Tasks")
}
NavigationView {
ShopView()
}
.tabItem {
Image(systemName: "cart.fill")
Text("Shop")
}
}
.environment(\.colorScheme, isDarkMode ? .dark : .light)
And now I want to add an if statement to .environment. So like if Default: .environment(.colorScheme, isDarkMode ? .dark : .light)
How can I do this?
Use #Environment to call the current color scheme. Then you can create a color variable.
struct ContentView: View {
#Environment(\.colorScheme) private var colorScheme
var body: some View {
TabView {
NavigationView {
TasksView()
}
.tabItem {
Image(systemName: "bookmark")
Text("Tasks")
}
.foregroundColor(titleColor) // <- here
NavigationView {
ShopView()
}
.tabItem {
Image(systemName: "cart.fill")
Text("Shop")
}
.foregroundColor(titleColor) // <- here
}
}
private var titleColor: Color {
switch colorScheme {
case .light:
return .red
case .dark:
return .yellow
#unknown default:
return .blue
}
}
}
Here's a possible solution. Use an ObservableObject class, store and save the variable. Set it as a StateObject and set as environmentObject in your App, then you can handle updates in your View by accessing the variable.
class ColorScheme: ObservableObject {
#AppStorage("dark") var dark = false
}
struct MyApp: App {
#StateObject var colorscheme = ColorScheme()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(colorscheme)
.colorScheme(colorscheme.dark ? .dark : .light)
}
}
}
struct ContentView: View {
#EnvironmentObject var colorscheme: ColorScheme
var body: some View {
NavigationView {
List {
Toggle("Color Scheme", isOn: colorscheme.$dark)
}
}
}
}

Enabling and Disabling CommandGroup Menu Items

I have a very simple sample macOS application with one custom menu command just in order to test my ideas as follows.
import SwiftUI
#main
struct MenuMonsterMacApp: App {
#State var fileOpenEnabled: Bool = true
var body: some Scene {
WindowGroup {
ContentView()
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
Button {
print("Open file, will you?")
} label: {
Text("Open...")
}
.keyboardShortcut("O")
.disabled(false)
}
}
}
}
And I want to enable and disable this command with a click of a button that is placed in ContentView. So I've created an ObservableObject class to observe the boolean value of the File Open command as follows.
import SwiftUI
#main
struct MenuMonsterMacApp: App {
#ObservedObject var menuObservable = MenuObservable()
#State var fileOpenEnabled: Bool = true
var body: some Scene {
WindowGroup {
ContentView()
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
Button {
print("Open file, will you?")
} label: {
Text("Open...")
}
.keyboardShortcut("O")
.disabled(!fileOpenEnabled)
}
}.onChange(of: menuObservable.fileOpen) { newValue in
fileOpenEnabled = newValue
}
}
}
class MenuObservable: ObservableObject {
#Published var fileOpen: Bool = true
}
In my ContentView, which virtually runs the show, I have the following.
import SwiftUI
struct ContentView: View {
#StateObject var menuObservable = MenuObservable()
var body: some View {
VStack {
Button {
menuObservable.fileOpen.toggle()
} label: {
Text("Click to disable 'File Open'")
}
}
}
}
If I click on the button, the boolean status of the menu command in question won't change. Is this a wrong approach? If it is, how can enable and disable the menu command from ContentView? Thanks.
To enable and disable the command with a click of a button that is placed in ContentView,
try the following approach, using passing environmentObject and a separate View for the
menu Button.
import SwiftUI
#main
struct MenuMonsterMacApp: App {
#StateObject var menuObservable = MenuObservable()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(menuObservable)
.frame(width: 480.0, height: 320.0)
}.commands {
CommandGroup(after: .newItem) {
OpenCommand().environmentObject(menuObservable)
}
}
}
}
struct OpenCommand: View {
#EnvironmentObject var menuObservable: MenuObservable
var body: some View {
Button {
print("Open file, will you?")
} label: {
Text("Open...")
}
.disabled(!menuObservable.fileOpen)
.keyboardShortcut("O")
}
}
class MenuObservable: ObservableObject {
#Published var fileOpen: Bool = true
}
struct ContentView: View {
#EnvironmentObject var menuObservable: MenuObservable
var body: some View {
VStack {
Button {
menuObservable.fileOpen.toggle()
} label: {
Text("Click to disable 'File Open'")
}
}
}
}

SwiftUI - Picker .onChange and didSet

I'm trying to achieve the behavior in the attached GIF:
Sorry for the High Speed, I had to compress it dramatically to be able to upload it here. The App is "Documents" from Readdle if you want to have a look on your own.
Anyways: I'm exactly trying to achieve this behavior (sorting and filtering, including the dynamic arrow up down icon).
I tried the following approach, however I'm not able to achieve this "ontap" expierience. On Change only triggers when I change the value but when I want to sort an existing value ascending and descending it's not working (which is obvious because it's not changing). I already played around with "didSet" but this also did not work.
Do you have an idea how this can be accomplished?
Below is my code:
import SwiftUI
struct ContentView: View {
#State var selection = 0
#State var sortByAsc = true
#State var filterColumn = "A"
//Test to set case via picker but picter doesnt execute didSet
#State var myFilterTest: MyFilters = .alphabetical {
didSet {
switch myFilterTest {
case .creationDate:
sortByAsc.toggle()
print("c")
case .rating:
sortByAsc.toggle()
print("b")
case .alphabetical:
sortByAsc.toggle()
print("a")
}
}
}
var body: some View {
NavigationView {
Text("Hello, World!")
.padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Menu(content: {
Picker("My Picker", selection: $selection) {
Label("Title", systemImage: sortByAsc ? "arrow.down" : "arrow.up")
.tag(0)
Label("Rating", systemImage: sortByAsc ? "arrow.down" : "arrow.up")
.tag(1)
.onTapGesture {
print("tap")
}
}
.onChange(of: selection) { tag in
print("Selected Tag: \(tag)")
sortByAsc.toggle()
if(tag == 0) {
filterColumn = "Title"
}
if(tag == 1) {
filterColumn = "Rating"
}
}
}, label: {
Image(systemName: "ellipsis.circle")
})
}
}
}
}
}
enum MyFilters: CaseIterable {
case alphabetical
case rating
case creationDate
}
Solved It. Here's the Code:
struct PickerView: View {
#State private var pickerIndex = 0
#State private var previousPickerIndex = 0
#State var sortByAsc = true
var body: some View {
let pickerSelection = Binding<Int>(get: {
return self.pickerIndex
}, set: {
self.pickerIndex = $0
if(pickerIndex == previousPickerIndex) {
sortByAsc.toggle()
}
previousPickerIndex = pickerIndex
})
NavigationView {
Text("Hello, World!")
.padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Menu(content: {
Picker("My Picker", selection: pickerSelection) {
ForEach(0..<4, id: \.self) { index in
Label("Title \(index)", systemImage: getSortingImage(menuItem: index))
.tag(index)
}
}
}, label: {
Image(systemName: "ellipsis.circle")
})
}
}
}
}
func getSortingImage(menuItem: Int) -> String {
if(menuItem == pickerIndex) {
if(sortByAsc) {
return "arrow.down"}
else {
return "arrow.up"
}
}
else {
return ""
}
}
}

How to toggle the visibility of the third pane of NavigationView?

Assuming the following NavigationView:
Struct ContentView: View {
#State var showRigthPane: Bool = true
var body: some View {
NavigationView {
Sidebar()
MiddlePane()
RightPane()
}.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: toggleSidebar, label: {Image(systemName: "sidebar.left")})
}
ToolbarItem(placement: .primaryAction) {
Button(action: self.toggleRightPane, label: { Image() })
}
}
}
private func toggleRightPane() {
// ?
}
// collapsing sidebar - this works
private func toggleSidebar() {
NSApp.keyWindow?.initialFirstResponder?.tryToPerform(
#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
}
How can I implement the toggleRightPane() function to toggle the visibility of the right pane?
Updated to use a calculated property returning two different navigation views. Still odd behavior with sidebar, but with a work-around it is functional. Hopefully someone can figure out the sidebar behavior.
struct ToggleThirdPaneView: View {
#State var showRigthPane: Bool = true
var body: some View {
VStack {
navigationView
}
.navigationTitle("Show and Hide")
}
var navigationView : some View {
if showRigthPane {
return AnyView(NavigationView {
VStack {
Text("left")
}
.toolbar {
Button(action: { showRigthPane.toggle() }) {
Label("Add Item", systemImage: showRigthPane ? "rectangle.split.3x1" : "rectangle.split.2x1")
}
}
Text("middle")
}
)
} else {
return AnyView(NavigationView {
VStack {
Text("left")
}
.toolbar {
Button(action: { showRigthPane.toggle() }) {
Label("Add Item", systemImage: showRigthPane ? "rectangle.split.3x1" : "rectangle.split.2x1")
}
}
Text("middle")
Text("right")
})
}
}
}
Try the following (cannot test)
struct ContentView: View {
#State private var showRigthPane = true
var body: some View {
NavigationView {
Sidebar()
MiddlePane()
if showRigthPane { // << here !!
RightPane()
}
}.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: self.toggleRightPane, label: { Image() })
}
}
}
private func toggleRightPane() {
withAnimation {
self.showRigthPane.toggle() // << here !!
}
}
}

Change State with DocumentPicker SwiftUI

I'm trying to get a List View to appear after selecting a document with documentPicker. Getting the following error...
Fatal error: No ObservableObject of type Switcher found.
A View.environmentObject(_:) for Switcher may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros/Monoceros-30.4/Core/EnvironmentObject.swift, line 55
It seems like I should use an EnviromentObject binding to have all views be able to read, access and update the Switcher class. Under the Coordinator Class in CSVDocumentPicker.swift is where things seem to go wrong.
I'm using #EnvironmentObject var switcher:Switcher and using the documentPicker function to toggle the switcher state so the Lists View will be displayed. I'm stumped.
SceneDelegate.swift
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var switcher = Switcher()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView().environmentObject(Switcher())
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(switcher))
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
}
func sceneDidBecomeActive(_ scene: UIScene) {
}
func sceneWillResignActive(_ scene: UIScene) {
}
func sceneWillEnterForeground(_ scene: UIScene) {
}
func sceneDidEnterBackground(_ scene: UIScene) {
}
}
CSVDocumentPicker.swift
import Combine
import SwiftUI
class Switcher: ObservableObject {
var didChange = PassthroughSubject<Bool, Never>()
var isEnabled = false {
didSet {
didChange.send(self.isEnabled)
}
}
}
struct CSVDocumentPicker: View {
#EnvironmentObject var switcher:Switcher
#State private var isPresented = false
var body: some View {
VStack{
Text("csvSearch")
Button(action: {self.isPresented = true
})
{Text("import")
Image(systemName: "folder").scaledToFit()
}.sheet(isPresented: $isPresented) {
() -> DocumentPickerViewController in
DocumentPickerViewController.init(onDismiss: {
self.isPresented = false
})
}
if switcher.isEnabled {
ListView()
}
}
}
}
struct CSVDocumentPicker_Previews: PreviewProvider {
static var previews: some View {
CSVDocumentPicker().environmentObject(Switcher())
}
}
/// Wrapper around the `UIDocumentPickerViewController`.
struct DocumentPickerViewController {
private let supportedTypes: [String] = ["public.item"]
// Callback to be executed when users close the document picker.
private let onDismiss: () -> Void
init(onDismiss: #escaping () -> Void) {
self.onDismiss = onDismiss
}
}
// MARK: - UIViewControllerRepresentable
extension DocumentPickerViewController: UIViewControllerRepresentable {
typealias UIViewControllerType = UIDocumentPickerViewController
func makeUIViewController(context: Context) -> DocumentPickerViewController.UIViewControllerType {
let documentPickerController = UIDocumentPickerViewController(documentTypes: supportedTypes, in: .import)
documentPickerController.allowsMultipleSelection = false
documentPickerController.delegate = context.coordinator
return documentPickerController
}
func updateUIViewController(_ uiViewController: DocumentPickerViewController.UIViewControllerType, context: Context) {}
// MARK: Coordinator
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIDocumentPickerDelegate, ObservableObject {
#EnvironmentObject var switcher:Switcher
var parent: DocumentPickerViewController
init(_ documentPickerController: DocumentPickerViewController) {
parent = documentPickerController
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
globalPathToCsv = url
loadCSV()
switcher.isEnabled.toggle()
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
parent.onDismiss()
}
}
}
ContentView.swift
import SwiftUI
import UIKit
var globalPathToCsv:URL!
var csvArray = [[String:String]]()
var csv = CSVaccessability()
func loadCSV(){
csv.csvToList()
// print(csvArray)
}
struct ContentView: View {
#EnvironmentObject var switcher:Switcher
var body: some View {
VStack{
CSVDocumentPicker().environmentObject(Switcher())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(Switcher())
}
}
ListView.swift
import SwiftUI
struct ListView: View {
var body: some View {
HStack{
List {
ForEach(csvArray, id:\.self) { dict in Section {DataList(dict: dict)} }
}
}}
}
struct DataList : View {
#State var dict = [String: String]()
var body: some View {
let keys = dict.map{$0.key}
let values = dict.map {$0.value}
return ForEach(keys.indices) {index in
HStack {
Text(keys[index])
Text("\(values[index])")
}
}
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
ListView()
}
}
CSVaccessability.swift
import Foundation
import SwiftCSV
var csvData:[[String]]!
var headers:[String] = []
class CSVaccessability {
var numberOfColumns:Int!
var masterList = [[String:Any]]()
func csvToList(){
if let url = globalPathToCsv {
do {
print(url)
let csvFile: CSV = try CSV(url: globalPathToCsv)
let csv = csvFile
//print(stream)
//print(csvFile)
headers = csv.header
csvArray=csv.namedRows
} catch {print("contents could not be loaded")}}
else {print("the URL was bad!")}
}
}
I've imported SwiftCSV for this project...
Created a new class...
ToggleView.swift
import Foundation
class ToggleView: ObservableObject {
#Published var toggleView: Bool = false
}
Added the Environment Object to ContentView.swift
#EnvironmentObject var viewToggle: ToggleView
Also added .environmentObject(ToggleView()) to any view that would be called and cause a crash the crash logs helped with this...
Text("csvSearch")
Button(action: {self.isPresented = true
self.viewToggle.toggleView.toggle()
// self.switcher = true
})
{Text("import")
Image(systemName: "folder").scaledToFit()
}.sheet(isPresented: $isPresented) {
() -> DocumentPickerViewController in
DocumentPickerViewController.init()
}
if self.picker {
DocumentPickerViewController().environmentObject(ToggleView())
}
if self.viewToggle.toggleView{
ListView()
}
}
}
}
Did you ever get this working? The only problem I found was with the line var csv = CSVaccessability() in the ContentView. CSVaccessability does not exist.
This is my solution for the Catalyst app for Mac, but to avoid pressing theImage (systemName: "book")button a second time to update the data in the text fields, I have implemented a hidden view in GeoFolderReadFileView to force the view update.
//File: GeoFolderCodStruct
import Foundation
struct GeoFolderCodStruct:Codable {
var isActive:Bool = true
var dataCreazione:Date = Date()
var geoFolderPath:String = ""
var nomeCartella:String = ""
var nomeCommittente:String = ""
var nomeArchivio:String = ""
var note:String = ""
var latitudine:Double? = nil
var longitudine:Double? = nil
var radiusCircle:Int16? = nil
//Roma 42.1234 13.1234
}
//File: PickerForReadFile
import SwiftUI
final class PickerForReadFile: NSObject, UIViewControllerRepresentable, ObservableObject {
#Published var geoFolder = GeoFolderCodStruct()
lazy var viewController:UIDocumentPickerViewController = {
let vc = UIDocumentPickerViewController(documentTypes: ["geof"], in: .open)
vc.allowsMultipleSelection = false
vc.delegate = self
return vc
}()
func makeUIViewController(context: UIViewControllerRepresentableContext<PickerForReadFile>) -> UIDocumentPickerViewController {
viewController.delegate = self
return viewController
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<PickerForReadFile>) {
print("updateUIViewController")
}
}
extension PickerForReadFile: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
if urls.count > 0 {
DispatchQueue.main.async {
let url = urls[0]
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let jsonData = try decoder.decode(GeoFolderCodStruct.self, from: data)
self.geoFolder = jsonData
print("geoFolder: \(self.geoFolder.nomeArchivio)")
} catch {
print("error:\(error)")
}
}
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
controller.dismiss(animated: true) {
print("Cancel from picker view controller")
}
}
}
//File: GeoFolderReadFileView
import SwiftUI
struct GeoFolderReadFileView: View {
#ObservedObject var picker = PickerForReadFile()
#Binding var geoFolder: GeoFolderCodStruct
var body: some View {
VStack(alignment: .trailing){
Button(action: {
#if targetEnvironment(macCatalyst)
print("Press open file")
let vc = UIApplication.shared.windows[0].rootViewController!
vc.present(self.picker.viewController, animated: true) {
self.geoFolder = self.picker.geoFolder
}
#endif
}) {
Image(systemName: "book")
}
urlPickedView()
.hidden()
}
}
private func urlPickedView() -> some View {
DispatchQueue.main.async {
let geoF = self.picker.geoFolder
print("Committente: \(geoF.nomeCommittente) - Archivio: \(geoF.nomeArchivio)")
self.geoFolder = geoF
}
return TextField("", text: $geoFolder.geoFolderPath)
}
}
//File: ContentView
import SwiftUI
struct ContentView: View {
#State private var geoFolder = GeoFolderCodStruct()
var body: some View {
VStack {
HStack {
Text("Open GeoFolder File:")
.padding()
Spacer()
GeoFolderReadFileView(geoFolder: $geoFolder)
.padding()
}
.padding()
Group {
TextField("", text: $geoFolder.geoFolderPath)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
TextField("", text: $geoFolder.nomeCartella)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
TextField("", text: $geoFolder.nomeCommittente)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
TextField("", text: $geoFolder.nomeArchivio)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
TextField("", text: $geoFolder.note)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
and the last, the json file to read for test the code.
{
"nomeCommittente" : "Appple",
"note" : "Image from Cupertino (CA).",
"latitudine" : 37.332161,
"longitudine" : -122.030352,
"nomeCartella" : "Foto",
"geoFolderPath" : "\/Users\/cesare\/Desktop",
"radiusCircle" : 50,
"dataCreazione" : "20\/03\/2020",
"nomeArchivio" : "AppleCampus-Image",
"isActive" : true
}
I was unable to implement the solution proposed by #Mdoyle1. I hope someone can edit the code to make it work as it should, without create hidden view.

Resources