Swift iOS中的TextField Draggable

4
我希望能够在视图中拖动文本框,但我的代码有些小问题。
以下是我的代码:
   override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        var touch : UITouch! = touches.first as! UITouch

        location = touch.locationInView(self.view)

        bottomTextField.center = location
    }

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

        var touch : UITouch! = touches.first as! UITouch

        location = touch.locationInView(self.view)

        bottomTextField.center = location
    }

问题是如果我试图触摸文本字段并拖动,它就不起作用。但如果我只是在其他地方触摸并拖动手指,那么文本字段开始拖动。我希望只有当我触摸到那个文本字段时才能拖动它。
2个回答

9

您可以通过为文本框添加手势来实现此功能:

override func viewDidLoad() {
    super.viewDidLoad()


    var gesture = UIPanGestureRecognizer(target: self, action: Selector("userDragged:"))
    bottomTextField.addGestureRecognizer(gesture)
    bottomTextField.userInteractionEnabled = true
}

func userDragged(gesture: UIPanGestureRecognizer){
    var loc = gesture.locationInView(self.view)
    self.bottomTextField.center = loc

}

1
如果有帮助的话,以下是适用于Swift 4.0和5.0的已接受答案的更新工作版本。
override func viewDidLoad() {
    super.viewDidLoad()

    //Draggable textfields
    let gesture = UIPanGestureRecognizer(target: self, action: #selector(userDragged(gesture:)))

    bottomTextView.addGestureRecognizer(gesture)
            bottomTextView.isUserInteractionEnabled = true

}

@objc func userDragged(gesture: UIPanGestureRecognizer){
    let loc = gesture.location(in: self.view)
    self.bottomTextView.center = loc

}

解释一下为什么进行了更新会很有帮助。我猜测这是为了使其与最新的Swift版本保持同步。您也可以使用这个新版本编辑原始答案。 - Nate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接