gpt4 book ai didi

ios - UIImages 或 UIViews 在 iOS Swift 中不会相互碰撞?

转载 作者:行者123 更新时间:2023-11-28 14:54:21 26 4
gpt4 key购买 nike

我正在尝试使用平移手势使两个 UIView 相互碰撞。现在我可以拖动一个 View ,但是当将 View 拖动到下一个 View 时,它会相互碰撞。它落后于其他 View 。

截图结果如下:

screenshot

这是我用来拖动、平移和碰撞物理属性的代码。

import UIKit

class ViewController: UIViewController {

var greenSquare: UIView?
var redSquare: UIView?
var animator: UIDynamicAnimator?
var snap: UISnapBehavior!
var panGesture = UIPanGestureRecognizer()


@IBAction func pan(_ sender: UIPanGestureRecognizer) {

let tapPoint: CGPoint = sender.location(in: view)

if (snap != nil) {
animator?.removeBehavior(snap)
}

snap = UISnapBehavior(item: greenSquare!, snapTo: tapPoint)
animator?.addBehavior(snap)

}

override func viewDidLoad() {
super.viewDidLoad()

var dimen = CGRect(x: 25, y: 25, width: 120, height: 120)
greenSquare = UIView(frame: dimen)
greenSquare?.backgroundColor = UIColor.green

dimen = CGRect(x: 130, y: 25, width: 100, height: 100)
redSquare = UIView(frame: dimen)
redSquare?.backgroundColor = UIColor.red

self.view.addSubview(greenSquare!)
self.view.addSubview(redSquare!)

animator = UIDynamicAnimator(referenceView: self.view)

let gravity = UIGravityBehavior(items: [greenSquare!, redSquare!])
let direction = CGVector(dx: 0.0, dy: 1.0)
gravity.gravityDirection = direction

let boundries = UICollisionBehavior(items: [greenSquare!, redSquare!])
boundries.translatesReferenceBoundsIntoBoundary = true

let bounce = UIDynamicItemBehavior(items: [greenSquare!, redSquare!])
bounce.elasticity = 0.5



animator?.addBehavior(bounce)
animator?.addBehavior(boundries)
animator?.addBehavior(gravity)


panGesture = UIPanGestureRecognizer(target: self, action:#selector(draggedView(sender:)))
greenSquare?.isUserInteractionEnabled = true
greenSquare?.addGestureRecognizer(panGesture)

}

@objc func draggedView(sender:UIPanGestureRecognizer){
let translation = sender.translation(in: self.view)
greenSquare?.center = CGPoint(x: (greenSquare?.center.x)! + translation.x, y: (greenSquare?.center.y)! + translation.y)
sender.setTranslation(CGPoint.zero, in: self.view)
}



}//class`

任何人都可以帮我解决这个问题。

最佳答案

问题是动画师只识别在 greenSquare 原点的碰撞。在这种情况下,它位于屏幕顶部。您可以在移动 greenSquare 后更新动画器上的碰撞位置。添加 animator?.updateItem(usingCurrentState: greenSquare!)draggedView 方法的末尾。您不需要为此使用 UISnapBehavior,因此您可以删除代码顶部的 IBAction func pan 方法。 updateItem(usingCurrentState:) 调用将在您手动移动 View 时重置碰撞屏障所在的位置,而这不是由物理引擎完成的。

关于ios - UIImages 或 UIViews 在 iOS Swift 中不会相互碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49535257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com