在 SwiftUI 中为 Button 创建扩展而苦苦挣扎
Struggling with creating extension for Button in SwiftUI
我一直在尝试做一个扩展来改变按钮的创建方式,但没有成功。
通常制作按钮的方法是这样的:
Button {
print("pressed")
} label: {
Label("Button", systemImage: "person")
}
但是我希望能够创建这样的按钮:
Button("Button", systemImage: "person") {
print("pressed")
}
这可能吗?如果是这样,如何?任何帮助将不胜感激。
本期的主要 non-obvious 部分是确认扩展中新自定义 init
的泛型与 SwiftUI Button
中使用的泛型一致 Button
,因为使用了相同的名称 Label
用于不同的事物。
这是找到的解决方案的主要部分:
init(_ title: LocalizedStringKey, systemImage: String, action: @escaping () -> Void)
where Label == SwiftUI.Label<Text, Image> {
我一直在尝试做一个扩展来改变按钮的创建方式,但没有成功。
通常制作按钮的方法是这样的:
Button {
print("pressed")
} label: {
Label("Button", systemImage: "person")
}
但是我希望能够创建这样的按钮:
Button("Button", systemImage: "person") {
print("pressed")
}
这可能吗?如果是这样,如何?任何帮助将不胜感激。
本期的主要 non-obvious 部分是确认扩展中新自定义 init
的泛型与 SwiftUI Button
中使用的泛型一致 Button
,因为使用了相同的名称 Label
用于不同的事物。
这是找到的解决方案的主要部分:
init(_ title: LocalizedStringKey, systemImage: String, action: @escaping () -> Void)
where Label == SwiftUI.Label<Text, Image> {