[英]SwiftUI disable drag function
我有一個簡單的視圖,其中包含一組允許拖動功能取決於條件的按鈕。 我如何根據條件禁用.onDrag? .disabled只禁用點擊功能。
ScrollView
{
ForEach(animals, id: \.id)
{
animal in
Button(action:{})
{
Text(animal.name)
}
.disabled(!animal.isEnable)
.onDrag
{
let provider = NSItemProvider(object: animal.name as NSString )
provider.suggestedName = animal.name
return provider
}
}
}
這是一個帶有輔助修飾符的解決方案。 使用 Xcode 11.4 進行測試。
// @available(iOS 13.4, *) - needed for iOS
struct Draggable: ViewModifier {
let condition: Bool
let data: () -> NSItemProvider
@ViewBuilder
func body(content: Content) -> some View {
if condition {
content.onDrag(data)
} else {
content
}
}
}
// @available(iOS 13.4, *) - needed for iOS
extension View {
public func drag(if condition: Bool, data: @escaping () -> NSItemProvider) -> some View {
self.modifier(Draggable(condition: condition, data: data))
}
}
並更新您的代碼將是
ForEach(animals, id: \.id)
{
animal in
Button(action:{})
{
Text(animal.name)
}
.disabled(!animal.isEnable)
.drag(if: animal.isEnable) { // << here !!
let provider = NSItemProvider(object: animal.name as NSString )
provider.suggestedName = animal.name
return provider
}
}
.disable 會終止與視圖的交互,因此不會拖動,所以它可以滿足您的需要
你可以查看文檔
控制用戶是否可以與該視圖交互的視圖。 https://developer.apple.com/documentation/swiftui/list/disabled(_:)
我認為這里可能有一個小錯誤,最好確保正確發送了 isEnable 參數。
.disabled(!animal.isEnable)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.