[英]Is there a way to get isDisabled state from ButtonStyle in SwiftUI?
我正在制作自己的自定義按鈕樣式以簡化按鈕的外觀和感覺。 基於按鈕是否被禁用,我想改變外觀。 我發現能夠做到這一點的唯一方法是從頂部傳遞isDisabled
屬性。 有沒有辦法直接從ButtonStyle
得到這個?
struct CellButtonStyle: ButtonStyle {
// Passed from the top... can I get this directly from configuration?
let isDisabled: Bool
func makeBody(configuration: Self.Configuration) -> some View {
let backgroundColor = isDisabled ? Color.white : Color.black
return configuration.label
.padding(7)
.background(isDisabled || configuration.isPressed ? backgroundColor.opacity(disabledButtonOpacity) : backgroundColor)
}
}
實際問題是它會導致在創建按鈕時處理isDisabled
標志的重復代碼:
Button {
invitedContacts.insert(contact.identifier)
} label: {
Text(invitedContacts.contains(contact.identifier) ? "Invited" : "Invite")
}
// Passing down isDisabled twice! Would be awesome for the configuration to figure it out directly.
.disabled(invitedContacts.contains(contact.identifier))
.buttonStyle(CellButtonStyle(isDisabled: invitedContacts.contains(contact.identifier)))
您可以使用isEnabled
環境值,但它不能直接在按鈕樣式中工作,您需要一些子視圖。 這是一個可能的方法演示(您可以通過構造函數注入的所有附加參數)
使用 Xcode 12 / iOS 14 進行測試。
struct CellButtonStyle: ButtonStyle {
struct CellBackground: View {
@Environment(\.isEnabled) var isEnabled // << here !!
var body: some View {
Rectangle().fill(isEnabled ? Color.black : Color.yellow)
}
}
func makeBody(configuration: Self.Configuration) -> some View {
return configuration.label
.padding(7)
.background(CellBackground()) // << here !!
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.