0
我在该图像上有一个imageview和一个文本框。我使用下面的代码使textfield可拖动,但它可以拖动到屏幕中的任何位置。我希望textfield只能在imageview的限制内拖动。如果我取消注释,如果检查draagedView函数,textfield卡在图像视图的左侧,因为它们的x值相同。将限制设置为Swift中的可拖动项目
我发现这个解决方案,但不能修改它在我的项目上工作。 Use UIPanGestureRecognizer to drag UIView inside limited area
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let gesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView(_:)))
bottomTextField.addGestureRecognizer(gesture)
bottomTextField.isUserInteractionEnabled = true
}
func userDragged(gesture: UIPanGestureRecognizer){
let loc = gesture.location(in: self.view)
self.bottomTextField.center = loc
}
func draggedView(_ sender:UIPanGestureRecognizer) {
let compare = MyimageView.frame.maxX <= bottomTextField.frame.maxX
//if(MyimageView.frame.minX <= bottomTextField.frame.minX && compare)
// {
self.view.bringSubview(toFront: sender.view!)
let translation = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: self.view)
// }
}
当我改变文本字段的位置并进行更改时,文本字段再次转到图像视图的中心。我希望保持它的位置。我该如何解决这个问题?谢谢! –
这可能是自动布局约束覆盖您的翻译。我会提出这个问题作为一个新问题。 – ganzogo