我为自定义视图创建了onTapGesture(_:)
的自定义实现,但是,它没有按预期工作。我有一个@State
属性叫做action
它在按钮按完后被调用。它的功能应该是"附加功能"。无论按钮做什么。由于一些奇怪的原因,当我更新action
属性时,它没有反映出来。
ShowAlertButton()
.onTapGestureCustom {
print("*silent alarm*")
// I expect the view to print "*silent alarm*" when I press "sound alarm"
// However, it continues to print "ALERT!!!" which is the default value
}
struct ShowAlertButton: View {
@State private var action: () -> Void = { print("ALERT!!!") } // << default value
var body: some View {
Button {
// ... some code
action() // << additional functionality
} label: {
Text("Sound alarm")
}
}
// Custom implementation of onTapGesture(_:)
func onTapGestureCustom(_ action: @escaping () -> Void) -> some View {
self.action = action
return self
}
}
有没有人知道为什么action
变量没有被更新?
谢谢。
通过返回新创建的View并将action
变量更改为正常的实例属性,使此工作按预期进行。(感谢@Cora的提示!!)
struct ShowAlertButton: View {
private var action: () -> Void = { print("ALERT!!!") }
var body: some View {
Button {
// ... some code
action()
} label: {
Text("Sound alarm")
}
}
func onTapGestureCustom(_ newValue: @escaping () -> Void) -> some View {
return ShowAlertButton(action: newValue)
// or Self(action: newValue)
}
}