【问题标题】:Set limit to draggable item in Swift在 Swift 中设置可拖动项目的限制
【发布时间】:2016-11-10 19:45:36
【问题描述】:

我在该图像上有一个图像视图和一个文本字段。我使用下面的代码使文本字段可拖动,但它可以拖动到屏幕中的任何位置。我希望该文本字段只能在图像视图的限制下拖动。如果我在 draagedView 函数中检查时取消注释,则文本字段会卡在 imageview 的左侧,因为它们的 x 值变得相同。

我找到了这个解决方案,但无法修改它以适用于我的项目。 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)

    // }
}

【问题讨论】:

    标签: ios swift view imageview textfield


    【解决方案1】:

    主要问题是您在进行翻译之前检查位置。这意味着文本字段最终处于无效位置,此后将永远无法到达 if 块。

    这是解决问题的一种稍微不同的方法,意味着文本字段会到达限制的边缘:

    func draggedView(_ sender: UIPanGestureRecognizer) {
    
      guard let senderView = sender.view else {
        return
      }
    
      var translation = sender.translation(in: view)
    
      translation.x = max(translation.x, MyimageView.frame.minX - bottomTextField.frame.minX)
      translation.x = min(translation.x, MyimageView.frame.maxX - bottomTextField.frame.maxX)
    
      translation.y = max(translation.y, MyimageView.frame.minY - bottomTextField.frame.minY)
      translation.y = min(translation.y, MyimageView.frame.maxY - bottomTextField.frame.maxY)
    
      senderView.center = CGPoint(x: senderView.center.x + translation.x, y: senderView.center.y + translation.y)
      sender.setTranslation(.zero, in: view)
      view.bringSubview(toFront: senderView)
    }
    

    我还通过在顶部添加 guard 语句并删除强制展开来使其更安全。

    【讨论】:

    • 当我更改文本字段的位置并进行更改时,文本字段再次转到图像视图的中心。我希望它留在原地。我该如何解决?谢谢!
    • 可能是自动布局约束覆盖了您的翻译。我会将此作为一个新问题提出。
    • @EmreÖnder:删除此代码“view.bringSubview(toFront: senderView)”,它将起作用..
    • 太棒了!非常感谢
    猜你喜欢
    • 2020-04-24
    • 2013-11-27
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多