Skip to content

Instantly share code, notes, and snippets.

@Nicejinux
Forked from mrketchup/WobbleView.swift
Created July 31, 2019 15:33
Show Gist options
  • Save Nicejinux/86dd537f82ca4a1a5c736712a8b8e949 to your computer and use it in GitHub Desktop.
Save Nicejinux/86dd537f82ca4a1a5c736712a8b8e949 to your computer and use it in GitHub Desktop.
A super simple and performant way to make any view wobble in tvOS
//
// 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