当前位置 : 主页 > 手机开发 > 其它 >

TextField可在Swift iOS中拖拽

来源:互联网 收集:自由互联 发布时间:2021-06-11
我想在我的视图中拖动textField.但是我的代码问题很小. 我的代码 override func touchesBegan(touches: SetNSObject, withEvent event: UIEvent) { var touch : UITouch! = touches.first as! UITouch location = touch.locationInVi
我想在我的视图中拖动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

}
网友评论