结合 UIAttachmentBehavior 和 UICollisionBehavior
Posted
技术标签:
【中文标题】结合 UIAttachmentBehavior 和 UICollisionBehavior【英文标题】:Combining UIAttachmentBehavior and UICollisionBehavior 【发布时间】:2015-06-20 16:51:57 【问题描述】:使用 UIKit Dynamics 我想 以使用户可以拖动视图(使用 UIPanGestureRecognizer
)但不能离开特定区域。
问题出现了,当用户/UIView 与碰撞行为的边界发生碰撞时,就不可能进行垂直移动。
I.E.当与边界区域的左侧相撞时,一个“卡”在那里,不能上下移动,恰到好处。将 UIView 拖回到用于去那里的确切路径上。
非常感谢 UIDynamicItemBehavior 解决此问题的任何帮助(尝试了弹性、摩擦和阻力,但无济于事)。
【问题讨论】:
【参考方案1】:我认为您以错误的方式实现了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)
【讨论】:
以上是关于结合 UIAttachmentBehavior 和 UICollisionBehavior的主要内容,如果未能解决你的问题,请参考以下文章
将 CGAffineTransformScale 与 UIAttachmentBehavior (UIDynamicAnimator) 一起使用
从 UICollectionView 中的 UIAttachmentBehavior 中删除振荡
UIAttachmentBehavior 中的长度是如何确定的?