Skip to content

Instantly share code, notes, and snippets.

@karigrooms
Last active February 19, 2021 17:04
Show Gist options
  • Save karigrooms/6c5b16c2a9f0ae827d71d1652ba1056e to your computer and use it in GitHub Desktop.
Save karigrooms/6c5b16c2a9f0ae827d71d1652ba1056e to your computer and use it in GitHub Desktop.
SwiftUI button ViewModel example for Lessons in SwiftUI blog post (3rd example)
struct VrboButtonStyle: ButtonStyle {
let iconMode: UTButtonIconMode?
let inverse: Bool
let size: UTButtonSize
let type: UTButtonType
func makeBody(configuration: Configuration) -> some View {
ButtonStyleView(configuration: configuration,
type: type,
size: size,
inverse: inverse,
iconMode: iconMode)
}
}
private struct ButtonStyleView: View {
typealias ViewModel = ButtonViewModel
@Environment(\.isEnabled) private var isEnabled: Bool
let configuration: ButtonStyle.Configuration
let viewModel: ViewModel
init(configuration: ButtonStyle.Configuration,
type: ButtonType,
size: ButtonSize,
inverse: Bool,
iconMode: ButtonIconMode?) {
self.configuration = configuration
self.viewModel = ViewModel(iconMode: iconMode, inverse: inverse, size: size, type: type)
}
var body: some View {
configuration.label
.fixedSize()
.lineLimit(2)
.multilineTextAlignment(.center)
.frame(width: viewModel.width, height: viewModel.height)
.padding(viewModel.padding)
.background(viewModel.backgroundColor(for: isEnabled, isPressed: configuration.isPressed))
.foregroundColor(viewModel.foregroundColor(for: isEnabled, isPressed: configuration.isPressed))
.cornerRadius(viewModel.cornerRadius)
.modifier(VrboText(typeStyle: viewModel.typeStyle))
.overlay(
RoundedRectangle(cornerRadius: viewModel.cornerRadius)
.stroke(viewModel.borderColor(for: isEnabled, isPressed: configuration.isPressed), lineWidth: 1)
)
.accentColor(viewModel.accentColor(for: isEnabled, isPressed: configuration.isPressed))
.scaleEffect(viewModel.scaleEffect(for: isEnabled, isPressed: configuration.isPressed))
.animation(.spring())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment