我正在嘗試制作一個自定義按鈕,我可以在其中實作自己的功能,如下例所示:
MSButton {
print("hello")
}
問題是,我不斷收到Expression of type '(() -> Void)?' is unused警告,并且我添加的功能沒有激活。
這是我試圖實作這一點的代碼:
struct MSButton: View {
var action: (() -> Void)?
var body: some View {
Button() {
action // where I am getting the warning.
} label: {
Text("Button")
}
}
}
我錯過了什么可以讓我action正常作業?任何幫助將不勝感激。
uj5u.com熱心網友回復:
我能夠弄清楚。我的實作如下:
struct MSButton: View {
var action: (() -> Void)?
var body: some View {
Button() {
self.action!() // fixed line
} label: {
Text("Button")
}
}
}
它有效,雖然我不明白為什么它有效,而不是我在我的問題中寫的代碼。
uj5u.com熱心網友回復:
答案很簡單,你忘了把它作為一個函式來呼叫。因此,正確答案是self.action?()
我個人建議這樣設定
struct MSButton: View {
var action: (() -> Void) = { }
var body: some View {
Button() {
self.action()
} label: {
Text("Button")
}
}
}
uj5u.com熱心網友回復:
問題?在于使操作成為可選操作以及您如何呼叫操作。
選項1
struct MSButton: View {
var action: (() -> Void)?
var body: some View {
Button() {
//Check if there is an action set
if let action = action{
action()
}
} label: {
Text("Button")
}
//Safety measure so you dont have a button that looks like it has an action but doesn't
.disabled(action == nil)
}
}
選項 2
struct MSButton: View {
//Remove the optional
var action: () -> Void
var body: some View {
Button(action: action) {
Text("Button")
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/507544.html
