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? The .disabled only disable click function.
我有一个简单的视图,其中包含一组按钮,允许拖动功能取决于条件。如何根据情况禁用.onDrag?已禁用仅禁用点击功能。
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
}
}
}
更多回答
What about wrapping the .onDrag closure in an if statement?
将.onDrag闭包包装在If语句中怎么样?
Here is a solution with helper modifier. Tested with Xcode 11.4.
以下是使用辅助对象修改器的解决方案。使用Xcode11.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(_:)
I think there might be a small mistake here, better to be sure isEnable param is correctly sent.
我认为这里可能有一个小错误,最好确保正确发送了启用参数。
.disabled(!animal.isEnable)
Disabled usually won't work.
残障人士通常不会起作用。
Create an extension for a View and put if
为视图创建扩展并放置If
extension View {
@ViewBuilder func `if`<Content: View>(_ condition: @autoclosure () -> Bool, transform: (Self) -> Content) -> some View {
if condition() {
transform(self)
} else {
self
}
}
}
and use like this:
并像这样使用:
Button(//) {
//
}
.if(animal.isEnable, transform: { view in
view
.draggable()
// or .onDrag...
}
更多回答
disabled(_:)
does not work on onDrop
.
禁用(_:)在onDrop上不起作用。
disabled()
does indeed work if applied after the onDrag()
and kills the interaction(just tested on iOS16.4 sim). Keep in mind that not only the dragging, but also other interaction will be killed, like buttons etc.
如果在onDrag()和终止交互(刚刚在iOS16.4sim上测试)之后应用,Disable()确实可以工作。请记住,不只是拖动,其他交互也会被取消,如按钮等。
testing disabled()
on macOS 12 and 13 showed no effect to .onDrag()
.
在MacOS 12和13上测试禁用()对.onDrag()没有影响。
My bad, I just noticed that I mixed onDrag
with onDrop
. Yes disabled()
works for onDrag
, but not onDrop
.
我的错,我刚刚注意到我把onDrag和onDrop混在了一起。是的,Disable()适用于onDrag,但不适用于onDrop。
我是一名优秀的程序员,十分优秀!