I have the following Swift script for changing scroll bars visibility in macOS:
import Foundation
func getSelectedValue() -> String {
if CommandLine.argc < 2 {
print("No arguments passed. Please pass one of the following values: \"Always\", \"Automatic\", \"WhenScrolling\".")
exit(1)
}
let args = CommandLine.arguments
let value = args[1]
if value != "Always" && value != "Automatic" && value != "WhenScrolling" {
return "Automatic"
}
return value
}
func setScrollBars(_ value: String) {
let domain = "AppleShowScrollBars"
UserDefaults.standard.setPersistentDomain(
[domain: Optional(value) as Any],
forName: UserDefaults.globalDomain
)
let notifyEvent = Notification.Name("AppleShowScrollBarsSettingChanged")
DistributedNotificationCenter.default().post(name: notifyEvent, object: nil)
}
let value = getSelectedValue()
setScrollBars(value)
Usage example:
./set-scroll-bars Always
For some reason, running this script also causes a reset of the input source settings to their defaults:
I don’t know why it happens because I don’t see any code that is responsible for input source settings.
>Solution :
You’re updating the entire global domain to contain just one setting. All other settings in the global domain, including the input source settings, are discarded.
You need to use UserDefaults.sharedDefaults.persistentDomain(forName: UserDefaults.globalDomain) to get a dictionary containing the current settings in the global domain, and update that dictionary.
if var settings = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain) {
settings["AppleShowsScrollBars"] = value
UserDefaults.standard.setPersistentDomain(settings, forName: UserDefaults.globalDomain)
}
