Skip to content

Instantly share code, notes, and snippets.

@karigrooms
Last active February 18, 2021 18:09
Show Gist options
  • Save karigrooms/354e322e929a13581c3a5cd245d008c1 to your computer and use it in GitHub Desktop.
Save karigrooms/354e322e929a13581c3a5cd245d008c1 to your computer and use it in GitHub Desktop.
SwiftUI button viewmodel example for Lessons in SwiftUI blog post (2nd example)
struct ButtonViewModel {
// ...
// MARK: State Styles
func backgroundColor(for isEnabled: Bool, isPressed: Bool) -> Color {
let styles = buttonTypeStyle(for: isEnabled, isPressed: isPressed)
return styles.backgroundColor.color.opacity(styles.buttonOpacity)
}
func borderColor(for isEnabled: Bool, isPressed: Bool) -> Color {
let styles = buttonTypeStyle(for: isEnabled, isPressed: isPressed)
return styles.borderColor.color
}
func foregroundColor(for isEnabled: Bool, isPressed: Bool) -> Color {
let styles = buttonTypeStyle(for: isEnabled, isPressed: isPressed)
return styles.textColor.color
}
func scaleEffect(for isEnabled: Bool, isPressed: Bool) -> CGFloat {
guard isEnabled else { return 1.0 }
return isPressed ? 0.99: 1.0
}
// MARK: State Helpers
func buttonTypeStyle(for isEnabled: Bool, isPressed: Bool) -> ButtonType.Style {
return isPressed ? buttonTypeStyle(forIsPressed: isPressed) : buttonTypeStyle(forIsEnabled: isEnabled)
}
func buttonTypeStyle(forIsEnabled isEnabled: Bool) -> ButtonType.Style {
guard let iconStyle = self.iconStyle else {
return isEnabled ? style : disabledStyle
}
return isEnabled ? iconStyle : disabledStyle
}
func buttonTypeStyle(forIsPressed isPressed: Bool) -> ButtonType.Style {
guard let iconStyle = self.iconStyle else {
return isPressed ? selectedStyle : style
}
return isPressed ? type.iconOnlySelectedStyle : iconStyle
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment