[英]Is there a way to make a UITextField move when user drags across screen?
I'm new to coding so I'm trying some small projects in swift.我是编码新手,所以我正在 swift 中尝试一些小项目。 Right now, I'm trying to make a text box inside the ViewController move when the user drags it along the screen.
现在,我试图让 ViewController 中的文本框在用户沿屏幕拖动时移动。 For the text box, I am currently using a UITextField but I have no idea how to program its movement according to drag.
对于文本框,我目前使用的是 UITextField 但我不知道如何根据拖动对其运动进行编程。
You'll want to add a UIPanGestureRecognizer to your view.您需要将 UIPanGestureRecognizer 添加到您的视图中。 There's all sorts of built in gesture recognizers for detecting various gestures like a tap or in this case a pan (drag).
有各种各样的内置手势识别器用于检测各种手势,如点击或在本例中为平移(拖动)。 You can check them out here: https://developer.apple.com/documentation/uikit/uigesturerecognizer
你可以在这里查看它们: https://developer.apple.com/documentation/uikit/uigesturerecognizer
Here we'll create a pan gesture recognizer, and add it to our view.在这里,我们将创建一个平移手势识别器,并将其添加到我们的视图中。 Assume myView is your UITextField.
假设 myView 是您的 UITextField。 A good place to do this is in your view controller's viewDidLoad() method.
执行此操作的好地方是您的视图控制器的 viewDidLoad() 方法。
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:)))
myView.addGestureRecognizer(pan)
The moment your finger touches the screen, we say that a touch sequence has begun.当您的手指触摸屏幕时,我们就说触摸序列已经开始。 The touch sequence ends when there are no more fingers on the screen.
当屏幕上没有更多手指时,触摸序列结束。 The pan gesture will determine if this touch sequence looks like a pan, and if so, the method handlePan will be called at various stages.
平移手势将确定此触摸序列是否看起来像平移,如果是,则将在各个阶段调用方法 handlePan。 Here, the gesture itself will be passed into the method, which we use to determine translation and move our view accordingly.
在这里,手势本身将被传递到方法中,我们用它来确定平移并相应地移动我们的视图。 Add this as a method of your view controller.
将此添加为您查看 controller 的方法。
@objc func handlePan(sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: sender.view)
self.myView.center.x += translation.x
self.myView.center.y += translation.y
sender.setTranslation(CGPoint.zero, in: sender.view)
}
The first line gets the translation in the view which the gesture is attached to (myView).第一行获取手势附加到的视图(myView)中的翻译。 We then adjust myView's position based on this translation, and then we set the translation to zero.
然后我们根据这个平移调整myView的position,然后我们将平移设置为零。 This is so that the next time this method is called, the translation will be a delta relative to the previous call.
这样下次调用此方法时,转换将是相对于前一次调用的增量。
The property sender.state
will tell you the state the gesture is currently in, for example, .began
, .changed
, .ended
.属性
sender.state
将告诉您手势当前所在的 state,例如.began
、 .changed
、 .ended
。 Since a pan is a continuous gesture, our method will be called many times, whenever there's a finger movement.由于平移是一个连续的手势,只要有手指移动,我们的方法就会被多次调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.