Change Buttonstyle Modifier Based on Light or Dark Mode in Swiftui

Change buttonStyle Modifier based on light or dark mode in SwiftUI

Just put that condition inside button style modifier, like

// ... other your code
})
.buttonStyle(CustomButtonStyle(scheme: colorScheme)) // << here !!

and in custom style

struct CustomButtonStyle: ButtonStyle {
var scheme: ColorScheme // << here !!

func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding(10)
Group {
if configuration.isPressed {
Circle() // example of internal dependency on scheme
.fill(self.scheme == .dark ? Color.offBlack : Color.offWhite)

// .. other code here
}

Changing buttonStyle for dark and light mode

Combined two styles of the same button for dark and light mode in the following way:

struct DarkOrLightBackground<S: Shape>: View {
@Environment(\.colorScheme) var colorScheme
var isHighlighted: Bool
var shape: S

var body: some View {
if colorScheme == .dark {
DarkBackground(isHighlighted: isHighlighted, shape: RoundedRectangle(cornerRadius: 25.0, style: .continuous))
} else {
LightBackground(isHighlighted: isHighlighted, shape: RoundedRectangle(cornerRadius: 25.0, style: .continuous))
}
}
}

struct DarkorLightButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding(.all, 40)
.contentShape(RoundedRectangle(cornerRadius: 25.0, style: .continuous))
.background(
DarkOrLightBackground(isHighlighted: configuration.isPressed, shape: RoundedRectangle(cornerRadius: 25.0, style: .continuous))
)
}
}

Then change the buttonStyle in DemoView to DarkorLightButtonStyle()

SwiftUI: Force View to use light or dark mode

.colorScheme() is deprecated does not work with the background well.

.preferredColorScheme() is the way now. Does the job with the background too.

TestView1()
.preferredColorScheme(.dark)

TestView2()
.preferredColorScheme(.light)

Developer docs for .preferredColorScheme()

How to set custom highlighted state of SwiftUI Button

Updated for SwiftUI beta 5

SwiftUI does actually expose an API for this: ButtonStyle.

struct MyButtonStyle: ButtonStyle {

func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding()
.foregroundColor(.white)
.background(configuration.isPressed ? Color.red : Color.blue)
.cornerRadius(8.0)
}

}

// To use it
Button(action: {}) {
Text("Hello World")
}
.buttonStyle(MyButtonStyle())



Related Topics



Leave a reply



Submit