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