TextField可在Swift iOS中拖拽

前端之家收集整理的这篇文章主要介绍了TextField可在Swift iOS中拖拽前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在我的视图中拖动textField.但是我的代码问题很小.

我的代码

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
    }

问题是,如果我试图触摸TextField并拖动它然后它不起作用.但是,如果我只是触摸其他地方并拖动我的手指然后TextField开始拖动.我想要只有触摸那个textFiel才能成功.

解决方法

您可以通过向文本字段添加手势来实现此目的:

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

}

猜你在找的Swift相关文章