use*_*874 8 drag-and-drop swiftui
我有一个简单的视图,其中包含一组按钮,允许根据条件拖动功能。如何根据条件禁用 .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
}
}
}
Run Code Online (Sandbox Code Playgroud)
Asp*_*eri 14
这是一个带有辅助修饰符的解决方案。使用 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))
}
}
Run Code Online (Sandbox Code Playgroud)
并更新你的代码是
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5787 次 |
| 最近记录: |