Swiftで遊ぼう! - 419 - UIDynamicAnimator再び 3
Swiftで遊ぼう!の古い記事-> Life-LOG OtherSide
下記のチュートリアルに取り組んでいます。
物理的な空間内で物体を落とすことができました。
次はユーザーのインタラクションを作ってみます。
まず物事を単純にするために、前回作った最初の衝突判定を消去します。
var firstContact = false
これは衝突判定用のプロパティなので要りません。
func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) { print("Boundary contact occurred - \(identifier)") print("Boundary contact occurred - \(identifier)") let collidingItem = item as! UIView collidingItem.backgroundColor = UIColor.yellowColor() UIView.animateWithDuration(0.3) { collidingItem.backgroundColor = UIColor.blueColor() } if (!firstContact) { firstContact = true let secondSquare = UIView(frame: CGRect(x: 30, y: 0, width: 100, height: 100)) secondSquare.backgroundColor = UIColor.grayColor() view.addSubview(secondSquare) collision.addItem(secondSquare) gravity.addItem(secondSquare) let attach = UIAttachmentBehavior(item: collidingItem, attachedToItem: secondSquare) animator.addBehavior(attach) } }
このメソッドも衝突時に灰色の四角形を作りだして同調させるメソッドですが消去してしまいます。
最初に「let」キーワードで青い四角形を作りましたが、これを消去して、次のプロパティを持たせます。
var square: UIView!
var snap: UISnapBehavior!
そして次のメソッドをオーバーライドするだけです。
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if (snap != nil) { animator.removeBehavior(snap) } let touch = touches.first! snap = UISnapBehavior(item: square, snapToPoint: touch.locationInView(view)) animator.addBehavior(snap) }
このメソッドに関する説明が少ないので理解しがたいのですが、snapというオブジェクトを作りますが、まずこれがnilじゃなく前にタップした状態がanimatorに残っていたらそれを除去して、新しいsnapを作ってやるって話ですが、まあなんとなく理解できる程度です。
ラン(Cmd + R)してみると次のようにタップしたところに青い四角形が動きます。
これでUIDynamicAnimatorのチュートリアルは終わります。