SwiftUI + 按钮的动态动作关闭 [英] SwiftUI + Dynamic action closure for Button
本文介绍了SwiftUI + 按钮的动态动作关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在探索 SwiftUI,并且能够创建 Button
的子类.
I am exploring SwiftUI and I was able to create a subclass of Button
.
子类包含 image
&title
属性,使其成为可重用的组件.
The subclass contains image
& title
properties, which makes it a reusable component.
但我无法为 Button
类定义动态动作行为.
But I am not able to define dynamic action behavior for Button
class.
请参考下面的代码.
圆形按钮的子类:
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)
}
}
}
示例用法:
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)
}
您将看到 action
块在此处打印一条消息.
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?
推荐答案
按钮更新 ...
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))
}
...
使用更新...
RoundButton(image: "chat", title: "message") {
print("Button pressed")
}
这篇关于SwiftUI + 按钮的动态动作关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文