简体   繁体   English

Swift iOS 中的 TextField 可拖动

[英]TextField Draggable in Swift iOS

I want to drag textField around my view.我想在我的视图周围拖动 textField。 but im having small problem with my code.但我的代码有小问题。

here my code这是我的代码

   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
    }

Problem is if i tried to touch on the TextField and drag then it doesn't work.问题是,如果我尝试触摸 TextField 并拖动,则它不起作用。 but if i just touch somewhere else and drag my finger then TextField start to drag.但如果我只是触摸其他地方并拖动我的手指然后 TextField 开始拖动。 i want t make it only if i touch on that textFiel.我只想在我触摸那个 textFiel 时才能做到。

You can achieve this by adding a gesture to the text field:您可以通过向文本字段添加手势来实现此目的:

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

}

If it helps anyone, following is an updated working version of the accepted answer for swift 4.0 and 5.0如果它对任何人有帮助,以下是 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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM