Swift碰撞边界不起作用

时间:2015-10-29 19:09:21

标签: ios swift uikit-dynamics

Swift 2.0,xcode 7,Ios 9

意图:我希望两个方块放到底部并停留在屏幕的底部。

现在发生了什么:没有错误阻止代码运行,重力工作正常,但碰撞似乎被忽略了。从而导致两个物体从屏幕底部落下。

注意:子类是UIView而不是UIViewController,这个视图是从segue访问的。

非常感谢!

代码:

import UIKit

class graphs: UIView {

//create two shapes
var greenSquare: UIView?
var redSquare: UIView?
var animator: UIDynamicAnimator?

override func drawRect(rect: CGRect) {

    var dimen = CGRectMake(25, 25, 60, 60)
    greenSquare = UIView(frame: dimen)
    greenSquare?.backgroundColor = UIColor.greenColor()

    dimen = CGRectMake(130, 25, 90, 90)
    redSquare = UIView(frame: dimen)
    redSquare?.backgroundColor = UIColor.redColor()

    //add them to the screen
    self.addSubview(greenSquare!)
    self.addSubview(redSquare!)

}

@IBAction func startbutton(sender: AnyObject) {
     //initialise the animator
    animator = UIDynamicAnimator()

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

    //add gravity
    let gravity = UIGravityBehavior(items: [greenSquare!, redSquare!])
    let direction = CGVectorMake(0.0, 1.0)
    gravity.gravityDirection = direction

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

   }
}

1 个答案:

答案 0 :(得分:0)

我通过将子类更改为UIViewController

来修复它

为什么之前的代码不起作用?

这是新代码:

import UIKit

class DrawView: UIViewController {

//Create two shapes
var greenSquare: UIView?
var redSquare: UIView?
var animator: UIDynamicAnimator?

override func viewDidLoad() {
    super.viewDidLoad()

}


@IBAction func startbutton(sender: UIButton) {

    //Create the shapes
    var dimen = CGRectMake(25, 25, 60, 60)
    greenSquare = UIView(frame: dimen)
    greenSquare?.backgroundColor = UIColor.greenColor()

    dimen = CGRectMake(130, 25, 90, 90)
    redSquare = UIView(frame: dimen)
    redSquare?.backgroundColor = UIColor.redColor()

    //Add them to the screen
    self.view.addSubview(greenSquare!)
    self.view.addSubview(redSquare!)

    //Initialize the animator
    animator = UIDynamicAnimator(referenceView: self.view)

    //Gravity
    let gravity = UIGravityBehavior(items: [greenSquare!, redSquare!] )
    let direction = CGVectorMake(0.0, 1.0)
    gravity.gravityDirection = direction

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

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

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

}