I use this code for the same situation as you. My iOS app lets the user choose whether to hide info on the Watch screen.
This is how I determine whether stuff should be hidden. Pass in your redactionReasons environment variable:
func getWidgetHideInfo(_ redactionReasons: RedactionReasons) -> Bool {
// Convenience method to decide whether or not to hide sensitive info when the system wants to.
// It is overridden by the iOS app setting: "Show information when device is locked/inactive".
return ((redactionReasons.contains(.privacy) || redactionReasons.contains(.placeholder)) && defaultsGetSettingsWidgetPrivacy() == false)
}
defaultsGetSettingsWidgetPrivacy()
gets the switch value from defaults; you may have it somewhere else. When the switch is off, it's false, and it means the user wants to hide their info, so this method is saying, when the system wants to hide stuff (.privacy
) or the user wants to hide stuff, return true, meaning yes we want to hide this data.
Put this code somewhere:
extension View {
/// Applies a modifier to a view conditionally.
///
/// - Parameters:
/// - condition: The condition to determine if the content should be applied.
/// - content: The modifier to apply to the view.
/// - Returns: The modified view.
@ViewBuilder func modifier<T: View>(
if condition: @autoclosure () -> Bool,
then content: (Self) -> T
) -> some View {
if condition() {
content(self)
} else {
self
}
}
/// Applies a modifier to a view conditionally.
///
/// - Parameters:
/// - condition: The condition to determine the content to be applied.
/// - trueContent: The modifier to apply to the view if the condition passes.
/// - falseContent: The modifier to apply to the view if the condition fails.
/// - Returns: The modified view.
@ViewBuilder func modifier<TrueContent: View, FalseContent: View>(
if condition: @autoclosure () -> Bool,
then trueContent: (Self) -> TrueContent,
else falseContent: (Self) -> FalseContent
) -> some View {
if condition() {
trueContent(self)
} else {
falseContent(self)
}
}
}
In your views, add a line like this so you have a variable you can use that says to hide or show the data:
let hideInfo: Bool = getWidgetHideInfo(redactionReasons)
And here's the fun part (if it works). Add the following modifier to something, like a Text() or an Image(), for example:
Image(systemName: "arrow.left.square.fill")
.font(.system(size: 32.0, weight: .regular))
.modifier(if: hideInfo) { $0.redacted(reason: .placeholder) } else: { $0.unredacted() }
Here it is with hideInfo = false:
And here it is with hideInfo = true: