I am exploring SwiftUI and I was able to create a subclass of Button.
The subclass contains image & title properties, which makes it a reusable component.
But I am not able to define dynamic action behavior for Button class.
Please refer code below.
Subclass of Round Button:
struct RoundButton: View {
var image: String
var title: String
var body: some View {
VStack {
Button(action: {
print("Button pressed")
}){
Image(image)
.renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.template))
}
.frame(width: 40, height: 40)
.background(Color.blue)
.cornerRadius(20)
.accentColor(.white)
Text(title)
.font(.footnote)
}
}
}
Example usage:
HStack(alignment: .center) {
Spacer(minLength: 50)
RoundButton(image: "chat", title: "message")
Spacer()
RoundButton(image: "call", title: "call")
Spacer()
RoundButton(image: "video", title: "video")
Spacer()
RoundButton(image: "mail", title: "mail")
Spacer(minLength: 50)
}
You will see that action block print a message here.
I would like to know how we can pass a function for a button's action event?
Button update ...
struct RoundButton: View {
var image: String
var title: String
var action: () -> Void
var body: some View {
VStack {
Button(action: action){
Image(image)
.renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.template))
}
...
Usage update ...
RoundButton(image: "chat", title: "message") {
print("Button pressed")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With