Created
August 17, 2021 05:02
-
-
Save victorBaro/fafefff90ebd8d7910749a98dfe437ac to your computer and use it in GitHub Desktop.
Dynamics Playground - PIP using field behaviors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
class DummyVC: UIViewController { | |
let margin: CGFloat = 20 | |
override func viewDidLoad() { | |
view.backgroundColor = .green | |
view.addSubview(pipView) | |
animator.setValue(true, forKey: "debugEnabled") | |
let scale = CGAffineTransform(scaleX: 0.5, y: 0.5) | |
for x in 0 ..< 2 { | |
for y in 0 ..< 2 { | |
let springField = UIFieldBehavior.springField() | |
springField.position = CGPoint(x: view.bounds.maxX * (CGFloat(x) + 0.5)/2, y: view.bounds.maxY * (CGFloat(y) + 0.5)/2) | |
springField.region = UIRegion(size: view.bounds.size.applying(scale)) | |
animator.addBehavior(springField) | |
springField.addItem(pipView) | |
} | |
} | |
animator.addBehavior(itemBehavior) | |
pipView.addGestureRecognizer(panGesture) | |
} | |
lazy var panGesture: UIPanGestureRecognizer = { | |
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(sender:))) | |
return panGesture | |
}() | |
lazy var animator:UIDynamicAnimator = { | |
return UIDynamicAnimator(referenceView: view) | |
}() | |
var pipView: UIView = { | |
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 200)) | |
view.backgroundColor = .red | |
return view | |
}() | |
lazy var itemBehavior: UIDynamicItemBehavior = { | |
let itemBehavior = UIDynamicItemBehavior(items: [pipView]) | |
// Adjust these values to change the "stickiness" of the view | |
itemBehavior.density = 0.001 | |
itemBehavior.resistance = 60 | |
itemBehavior.friction = 0.0 | |
itemBehavior.allowsRotation = false | |
return itemBehavior | |
}() | |
lazy var attachment: UIAttachmentBehavior = { | |
let attachment = UIAttachmentBehavior(item: pipView, attachedToAnchor: .zero) | |
attachment.length = 0 | |
return attachment | |
}() | |
@objc func handlePan(sender: UIPanGestureRecognizer) { | |
itemBehavior.action | |
let location = sender.location(in: view) | |
let velocity = sender.velocity(in: view) | |
switch sender.state | |
{ | |
case .began: | |
attachment.anchorPoint = location | |
animator.addBehavior(attachment) | |
case .changed: | |
attachment.anchorPoint = location | |
case .cancelled, .ended, .failed, .possible: | |
itemBehavior.addLinearVelocity(velocity, for: pipView) | |
animator.removeBehavior(attachment) | |
} | |
} | |
} | |
PlaygroundPage.current.liveView = DummyVC(nibName: nil, bundle: nil) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment