[英]SwiftUI disable drag function
I have a simple view which contains a group of Buttons which allow drag feature depends on condition.我有一个简单的视图,其中包含一组允许拖动功能取决于条件的按钮。 How can i disable.onDrag based on the condition?
我如何根据条件禁用.onDrag? The.disabled only disable click function.
.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
}
}
}
Here is a solution with helper modifier.这是一个带有辅助修饰符的解决方案。 Tested with Xcode 11.4.
使用 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))
}
}
and updated your code would be并更新您的代码将是
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 kills the interaction with the view therefore no dragging so it does what you need .disable 会终止与视图的交互,因此不会拖动,所以它可以满足您的需要
you can check the documentation你可以查看文档
A view that controls whether users can interact with this view.
控制用户是否可以与该视图交互的视图。 https://developer.apple.com/documentation/swiftui/list/disabled(_:)
https://developer.apple.com/documentation/swiftui/list/disabled(_:)
I think there might be a small mistake here, better to be sure isEnable param is correctly sent.我认为这里可能有一个小错误,最好确保正确发送了 isEnable 参数。
.disabled(!animal.isEnable)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.