【问题标题】:UIImages or UIViews are not colliding each other in iOS Swift?视图的图像在 iOS Swift 中不会相互碰撞?
【发布时间】:2018-03-28 12:58:31
【问题描述】:

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

这是截图结果:

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

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`

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

【问题讨论】:

    标签: ios swift xcode uiview uiimageview


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 1970-01-01
      • 2023-03-11
      • 2013-04-24
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多