[英]How do I add closures to Viewmodifiers in SwiftUI?
我在这里使用 ClearButton ViewModifier
.modifier(ClearButton(text: $someBinding))
但我想在清除文本字段后运行一个函数。 像这样或类似
.modifier(ClearButton(text: $someBinding)) {
print("")
}
是否可以?
您可以将函数作为参数传递,如下所示:
struct ClearButton: ViewModifier {
@Binding var text: String
var action: () -> Void = {} // pass the function here
public func body(content: Content) -> some View {
ZStack(alignment: .trailing) {
content
if !text.isEmpty {
Button(action: {
self.text = ""
action() // call the `action` here
}) {
Image(systemName: "delete.left")
.foregroundColor(Color(UIColor.opaqueSeparator))
}
.padding(.trailing, 8)
}
}
}
}
并将此修饰符应用于您的 TextField:
struct ContentView: View {
@State private var text = ""
var body: some View {
TextField("Some Text", text: $text)
.modifier(
ClearButton(text: $text) {
print("TextField cleared")
}
)
}
}
请注意,如果您想跳过尾随闭包的标签,则action
参数必须放在最后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.