2015-06-20 28 views
3

使用UIKit Dynamics我想結合UIAttachmentBehavior和UICollisionBehavior,讓用戶可以拖動視圖(使用UIPanGestureRecognizer)但不留下特定區域。結合使用UIAttachmentBehavior和UICollisionBehavior

問題出現時,當用戶/ UIView與碰撞行爲的邊界發生碰撞時,因爲沒有垂直移動是可能的。

I.E.當與邊界區域的左側碰撞時,一個「卡住」在那裏,不能向上或向下移動,恰到好處。將UIView拖回到用於去那裏的確切路徑上。

任何有關UIDynamicItemBehavior解決這個問題的幫助都會受到高度讚賞(試過彈性,摩擦和阻力,但無濟於事)。

enter image description here

回答

0

我認爲你在錯誤的方式來實現UIPanGestureRecognizer。試試下面的例子。只需創建一個新項目並將此代碼粘貼到您的ViewController中。如果您需要減少可拖動區域,則可以使用dragView功能。

import UIKit 

class ViewController: UIViewController, UICollisionBehaviorDelegate { 

    var collision: UICollisionBehavior! 
    var animator: UIDynamicAnimator! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let container = UIView(frame: CGRect(x: 30, y: 60, width: 300, height: 500)) 
     self.view.addSubview(container) 
     container.backgroundColor = .gray 

     self.animator = UIDynamicAnimator(referenceView: container); 
     //self.animator.setValue(true, forKey: "debugEnabled") 

     let greenBox = UIView(frame: CGRect(x: 60, y: 240, width: 50, height: 50)) 
     greenBox.backgroundColor = .green 
     container.addSubview(greenBox) 

     let blueBox = UIView(frame: CGRect(x: 10, y: 10, width: 50, height: 50)) 
     blueBox.backgroundColor = .blue 
     container.addSubview(blueBox) 

     let redBox = UIView(frame: CGRect(x: 200, y: 300, width: 50, height: 50)) 
     redBox.backgroundColor = .red 
     container.addSubview(redBox) 

     self.collision = UICollisionBehavior(items: [greenBox, blueBox, redBox]) 
     self.collision.translatesReferenceBoundsIntoBoundary = true 
     self.collision.collisionMode = .everything 
     self.animator.addBehavior(self.collision) 
     self.collision.collisionDelegate = self 


     let c = UIDynamicItemBehavior(items: [redBox]) 
     c.density = 10000 
     self.animator.addBehavior(c) 

     let noRotation = UIDynamicItemBehavior(items: [greenBox, blueBox]) 
     noRotation.allowsRotation = false 
     self.animator.addBehavior(noRotation) 

     let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.dragView(_:))) 
     greenBox.isUserInteractionEnabled = true 
     greenBox.addGestureRecognizer(panGesture) 

     let panGesture2 = UIPanGestureRecognizer(target: self, action: #selector(self.dragView(_:))) 
     blueBox.isUserInteractionEnabled = true 
     blueBox.addGestureRecognizer(panGesture2) 

    } 


    @objc func dragView(_ sender:UIPanGestureRecognizer){ 

     if let viewDrag = sender.view { 
      self.view.bringSubview(toFront: viewDrag) 
      let translation = sender.translation(in: self.view) 
      viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y) 
      sender.setTranslation(CGPoint.zero, in: self.view) 
      animator.updateItem(usingCurrentState: viewDrag) 
     } 
    } 

}