UICollisionBehavior 忽略屏幕边缘

Posted

技术标签:

【中文标题】UICollisionBehavior 忽略屏幕边缘【英文标题】:UICollisionBehavior Ignore Screen Edges 【发布时间】:2021-04-09 00:41:28 【问题描述】:

我有几个 UIView 在屏幕上连续移动。使用UICollisionBehavior 我可以防止视图相互碰撞,但我需要它们穿过屏幕的边缘(顶部、左侧、右侧、底部)。在下面的这个例子中,一旦它们碰到屏幕的底部边缘,它们就会相互弹开,然后最终就坐在那里。我尝试对 UIViews 进行子类化,并查看冲突是否仅适用于子类类型,但这不起作用。

如何防止 UIView 相互碰撞但仍让它们穿过屏幕边缘?

子类:

class CollisionView: UIView  // nothing special happens here except it's a subclass

代码:

lazy var redView: CollisionView = 
    let view = CollisionView()
    view.backgroundColor = .red
    return view
()

lazy var blueView: CollisionView = 
    let view = CollisionView()
    view.backgroundColor = .blue
    return view
()

lazy var yellowView: CollisionView = 
    let view = CollisionView()
    view.backgroundColor = .yellow
    return view
()

lazy var purpleView: CollisionView = 
    let view = CollisionView()
    view.backgroundColor = .purple
    return view
()

lazy var greenView: CollisionView = 
    let view = CollisionView()
    view.backgroundColor = .green
    return view
()

var arr = [CollisionView]()

var animator: UIDynamicAnimator!
var gravity: UIGravityBehavior!
var collider: UICollisionBehavior!
var bouncingBehavior  : UIDynamicItemBehavior!

override func viewDidLoad() 
    super.viewDidLoad()
    view.backgroundColor = .white
    
    addSubViews()
    
    addAnimatorAndBehaviors()


func addAnimatorAndBehaviors() 
    
    animator = UIDynamicAnimator(referenceView: self.view)
    
    gravity = UIGravityBehavior(items: arr)
    animator.addBehavior(gravity)
    
    collider = UICollisionBehavior(items: arr)
    collider.translatesReferenceBoundsIntoBoundary = true
    animator.addBehavior(collider)
    
    bouncingBehavior = UIDynamicItemBehavior(items: arr)
    bouncingBehavior.elasticity = 0.75
    animator.addBehavior(bouncingBehavior)


func addSubViews() 
    
    let size = CGSize(width: 50, height: 50)
    
    redView.frame = CGRect(origin: view.center, size: size)
    blueView.frame = CGRect(origin: view.center, size: size)
    yellowView.frame = CGRect(origin: view.center, size: size)
    purpleView.frame = CGRect(origin: view.center, size: size)
    greenView.frame = CGRect(origin: view.center, size: size)
    
    view.addSubview(redView)
    view.addSubview(blueView)
    view.addSubview(yellowView)
    view.addSubview(purpleView)
    view.addSubview(greenView)
    
    arr = [redView, blueView, yellowView, purpleView, greenView]

【问题讨论】:

【参考方案1】:

很容易解决,我只需要添加:

collider.collisionMode = .items

CollisionView 子类是不必要的

【讨论】:

以上是关于UICollisionBehavior 忽略屏幕边缘的主要内容,如果未能解决你的问题,请参考以下文章

结合 UIAttachmentBehavior 和 UICollisionBehavior

UICollisionBehavior 仅在第一次添加后有效

UIKit Dynamics UICollisionBehavior 无反弹的碰撞

LinearLayout 忽略边距

TextView 忽略左右边距

:hover 忽略边距