【发布时间】:2020-04-10 20:26:59
【问题描述】:
我正在探索 SwiftUI,并且能够创建 Button 的子类。
子类包含image & title 属性,这使它成为一个可重用的组件。
但我无法为 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)
}
}
}
使用示例:
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 块打印一条消息。
我想知道我们如何为按钮的动作事件传递函数?
【问题讨论】: