Last active
July 31, 2019 15:33
-
-
Save mrketchup/e172f26968c990e702ffb52e5f3c8b00 to your computer and use it in GitHub Desktop.
A super simple and performant way to make any view wobble in tvOS
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
// | |
// WobbleView.swift | |
// WobbleView | |
// | |
// Created by Matt Jones on 4/28/16. | |
// Copyright © 2016 WillowTree, Inc. All rights reserved. | |
// | |
import UIKit | |
class WobbleView: UIView { | |
var focusedFrameGuide: UILayoutGuide { | |
return renderedWobbleView.focusedFrameGuide | |
} | |
private var renderedWobbleView: UIImageView = { | |
let view = UIImageView() | |
view.adjustsImageWhenAncestorFocused = true | |
view.translatesAutoresizingMaskIntoConstraints = false | |
return view | |
}() | |
override func willMoveToSuperview(newSuperview: UIView?) { | |
super.willMoveToSuperview(newSuperview) | |
renderedWobbleView.removeFromSuperview() | |
renderedWobbleView.image = nil | |
} | |
override func didMoveToSuperview() { | |
super.didMoveToSuperview() | |
guard let superview = superview else { | |
return | |
} | |
superview.addSubview(renderedWobbleView) | |
renderedWobbleView.topAnchor.constraintEqualToAnchor(self.topAnchor).active = true | |
renderedWobbleView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor).active = true | |
renderedWobbleView.leftAnchor.constraintEqualToAnchor(self.leftAnchor).active = true | |
renderedWobbleView.rightAnchor.constraintEqualToAnchor(self.rightAnchor).active = true | |
} | |
override func didAddSubview(subview: UIView) { | |
super.didAddSubview(subview) | |
setNeedsLayout() | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { | |
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) | |
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, 0) | |
self.layer.hidden = false | |
self.layer.renderInContext(UIGraphicsGetCurrentContext()!) | |
let image = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
dispatch_async(dispatch_get_main_queue()) { | |
self.renderedWobbleView.image = image | |
self.hidden = true | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment