Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

ios - Question about .gesture(drag gesture) in swift ui

I am trying to detect when this text view has been swiped on. The code compiles fine, but I am not able to trigger the swipe on my actual device. When I swipe, nothing happens. Tap seems to work just fine. Can anyone let me know what I'm doing wrong in my code?

In case this matters, I'm developing a watch OS app in swift 5.3 with the latest Xcode.

var body: some View {

    Text(tempstring).onTapGesture { checkStateRoll() }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .gesture(DragGesture(minimumDistance: 10, coordinateSpace: .global)
     .onEnded { value in
                            let horizontalAmount = value.translation.width as CGFloat
                            let verticalAmount = value.translation.height as CGFloat
                            
                            if abs(horizontalAmount) > abs(verticalAmount) {
                                horizontalAmount < 0 ? leftswipe() : rightswipe()
                            } else {
                                verticalAmount < 0 ? upswipe() : downswipe()
                            }
                            tempstring = String(numdice) + "d" + String(typesofdice[typedice])
                            speaknumber()
                        }        ) 
    
    .background(progstate == 2 ? Color.blue : Color.red)
    }
}

Thanks a lot for any help. This has been stumping me for weeks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A couple of things:

  1. With respect to layout, setting a frame will no change the text size because the text sizes itself to its content. Use a greedy view like a ZStack if you want to take up all of the space.
  2. The sequence of the modifiers does matter. You read the order in which they are applied from bottom to top, so in this case they need to go on the stack.

Here is an example playground:

import SwiftUI
import PlaygroundSupport

struct V: View {
  var body: some View {
    ZStack {
      Color.red
      Text("Test")
    }
      .onTapGesture { print("tap") }
      .gesture(DragGesture(minimumDistance: 10, coordinateSpace: .global).onEnded { print($0)})

  }
}

let host = UIHostingController(rootView: V().frame(width: 500.0, height: 500.0))
host.preferredContentSize = CGSize(width: 300, height: 300)
PlaygroundPage.current.liveView = host

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...