我想在我的视图中拖动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才能成功。
答案 0 :(得分:7)
您可以通过向文本字段添加手势来实现此目的:
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 :(得分: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
}