Skip to content

Instantly share code, notes, and snippets.

@YanSte
Created February 17, 2021 00:08
Show Gist options
  • Save YanSte/6cbf72922b38ad8a92959de661fdc7ff to your computer and use it in GitHub Desktop.
Save YanSte/6cbf72922b38ad8a92959de661fdc7ff to your computer and use it in GitHub Desktop.
UIViewExtensions.swift
//
// UIViewExtensions.swift
//
// Created by DaRk-_-D0G on 24/07/2015.
// Copyright (c) 2015 DaRk-_-D0G. All rights reserved.
//
import UIKit
import QuartzCore
// MARK: - Extensions UIView BSFramework
public extension UIView {
/* --------------------------------------------------------------------------- */
// MARK: - Initilizers ( init )
/* --------------------------------------------------------------------------- */
/**
Initializes UIView
- parameter x: CGFloat
- parameter y: CGFloat
- parameter width: CGFloat
- parameter height: CGFloat
- returns: UIView
*/
public convenience init(
x: CGFloat,
y: CGFloat,
width: CGFloat,
height: CGFloat) {
self.init (frame: CGRect (x: x, y: y, width: width, height: height))
}
/**
Initializes UIView with superview
- parameter superView: UIView
- returns: UIView
*/
public convenience init(superView: UIView) {
self.init (frame: CGRect (origin: CGPointZero, size: superView.size))
}
/**
Initializes UIView with puts padding around the view
- parameter superView: UIView
- parameter padding: CGFloat
- returns: UIView
*/
public convenience init(superView: UIView, padding: CGFloat) {
self.init(frame: CGRect(x: superView.x + padding, y: superView.y + padding, width: superView.width - padding*2, height: superView.height - padding*2))
}
/* --------------------------------------------------------------------------- */
// MARK: - Size
/* --------------------------------------------------------------------------- */
/// With size
public var width:CGFloat {
get {
return self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
/// Height size
public var height:CGFloat {
get {
return self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
/// Size
public var size: CGSize {
get {
return self.frame.size
}
set {
self.frame = CGRect (origin: self.frame.origin, size: newValue)
}
}
/* --------------------------------------------------------------------------- */
// MARK: - Position
/* --------------------------------------------------------------------------- */
/// X position
public var x:CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame = CGRect (x: newValue, y: self.y, width: self.width, height: self.height)
}
}
/// Y position
public var y:CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame = CGRect (x: self.x, y: newValue, width: self.width, height: self.height)
}
}
/// Position
public var position: CGPoint {
get {
return self.frame.origin
} set (value) {
self.frame = CGRect (origin: value, size: self.frame.size)
}
}
/// Center X
public var centerX: CGFloat {
return self.center.x
}
/// Center Y
public var centerY: CGFloat {
return self.center.y
}
/**
Position Left / Droite
- returns: CGFloat
*/
public func leftPosition() -> CGFloat {
return self.x
}
/**
Position Right / Gauche
- returns: CGFloat
*/
public func rightPosition() -> CGFloat{
return self.x + self.width
}
/**
Position top
- returns: CGFloat
*/
public func topPosition() -> CGFloat{
return self.y
}
/**
Position bottom
- returns: CGFloat
*/
public func bottomPosition() -> CGFloat{
return self.y + self.height
}
/* --------------------------------------------------------------------------- */
// MARK: - Anchor Position
/* --------------------------------------------------------------------------- */
/**
Set Anchor position
- parameter anchorPosition: AnchorPosition
*/
public func setAnchorPosition (anchorPosition: AnchorPosition) {
self.layer.anchorPoint = anchorPosition.rawValue
}
/* --------------------------------------------------------------------------- */
// MARK: - NSLayoutConstraint
/* --------------------------------------------------------------------------- */
/**
Bound in side the superView
<br><br>Example : <br><br>[ SuperView H/W [ MyView H/W ] ] -> SuperView H/W = MyView H/W<br><br>
subview.boundInside(superView)<br><br>
- parameter superView: UIView / Size in superView
*/
public func boundInside(superView: UIView){
self.translatesAutoresizingMaskIntoConstraints = false
superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:["subview":self]))
superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:["subview":self]))
}
/**
Animate Constraint with duration
<br><br>example use : <br><br>self.nameInputConstraint.constant = 8<br><br>view.animateConstraintWithDuration()<br><br>
- parameter duration: NSTimeInterval
- parameter delay: NSTimeInterval
- parameter options: UIViewAnimationOptions
- parameter completion: (Bool) -> ())?
*/
public func applyAnimateConstraintWithDuration(
duration: NSTimeInterval = 0.5,
delay: NSTimeInterval = 0.0,
options: UIViewAnimationOptions = .TransitionNone,
completion: ((Bool) -> ())? = nil) {
UIView.animateWithDuration(duration, delay:delay, options:options, animations: { [weak self] in
self?.layoutIfNeeded() ?? ()
}, completion: completion)
}
/* --------------------------------------------------------------------------- */
// MARK: - Other ( Delete, image )
/* --------------------------------------------------------------------------- */
/**
Remove allSubView
*/
public func removeAllSubViews() {
for subView : AnyObject in self.subviews { subView.removeFromSuperview() }
}
/**
UIView to Image
- returns: UIImage
*/
func toImage () -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0)
drawViewHierarchyInRect(bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/* --------------------------------------------------------------------------- */
// MARK: - NIB
/* --------------------------------------------------------------------------- */
/**
Get view from nib, the first
- parameter nameFile: String
- returns: UIView
*/
public class func getViewFromNib(nameFile:String) -> UIView {
return UINib(nibName: nameFile, bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}
/**
Get views collection from nib
- parameter nameFile: String
- returns: [UIView]
*/
public class func getViewCollectionFromNib(nameFile:String) -> [UIView] {
return UINib(nibName: nameFile, bundle: nil).instantiateWithOwner(nil, options: nil) as! [UIView]
}
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Constraint
/* --------------------------------------------------------------------------- */
/**
Add Constrain to UIView
- parameter attribute: NSLayoutAttribute
- parameter relation: NSLayoutRelation
- parameter otherView: UIView
- parameter otherAttribute: NSLayoutAttribute
- parameter multiplier: CGFloat
- parameter constant: CGFloat
- parameter priority: UILayoutPriority
- parameter identifier: String?
- returns: NSLayoutConstraint
*/
public func constrain(
attribute: NSLayoutAttribute,
_ relation: NSLayoutRelation,
to otherView: UIView,
_ otherAttribute: NSLayoutAttribute,
times multiplier: CGFloat = 1,
plus constant: CGFloat = 0,
atPriority priority: UILayoutPriority = UILayoutPriorityRequired,
identifier: String? = nil)
-> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: self,
attribute: attribute,
relatedBy: relation,
toItem: otherView,
attribute: otherAttribute,
multiplier: multiplier,
constant: constant)
constraint.priority = priority
constraint.identifier = identifier
constraint.active = true
return constraint
}
/**
Add Constrain to UIView
- parameter attribute: NSLayoutAttribute
- parameter relation: NSLayoutRelation
- parameter constant: CGFloat
- parameter priority: UILayoutPriority
- parameter identifier: String?
- returns: NSLayoutConstraint
*/
public func constrain(
attribute: NSLayoutAttribute,
_ relation: NSLayoutRelation,
to constant: CGFloat,
atPriority priority: UILayoutPriority = UILayoutPriorityRequired,
identifier: String? = nil)
-> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: self,
attribute: attribute,
relatedBy: relation,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 0,
constant: constant)
constraint.priority = priority
constraint.identifier = identifier
constraint.active = true
return constraint
}
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Gesture
/* --------------------------------------------------------------------------- */
/**
Attaches a gesture recognizer **Tap** to the view.
- parameter tapNumber: Int <br> **Number of Tap**
- parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.**
- parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.**
*/
public func addTapGesture(tapNumber tapNumber: Int, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
}
/**
Attaches a gesture recognizer **Swipe** to the view.
- parameter direction: UISwipeGestureRecognizerDirection <br> **.Right .Left .Up .Down**
- parameter numberOfTouches: Int <br> **Number of touches for the swipe**
- parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.**
- parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.**
*/
public func addSwipeGesture(direction direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int, target: AnyObject, action: Selector) {
let swipe = UISwipeGestureRecognizer(target: target, action: action)
swipe.direction = direction
swipe.numberOfTouchesRequired = numberOfTouches
addGestureRecognizer(swipe)
userInteractionEnabled = true
}
/**
Attaches a gesture recognizer **Pan** to the view.
- parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.**
- parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.**
*/
public func addPanGesture(target target: AnyObject, action: Selector) {
let pan = UIPanGestureRecognizer(target: target, action: action)
addGestureRecognizer(pan)
userInteractionEnabled = true
}
/**
Attaches a gesture recognizer **Pinch** to the view.
- parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.**
- parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.**
*/
public func addPinchGesture(target target: AnyObject, action: Selector) {
let pinch = UIPinchGestureRecognizer(target: target, action: action)
addGestureRecognizer(pinch)
userInteractionEnabled = true
}
/**
Attaches a gesture recognizer **Long Press** to the view.
- parameter target: AnyObject <br> **Object recipient action messages sent by the recognizes gesture.**
- parameter action: Selector <br> **Method implemented by the target to handle the gesture recognized.**
*/
public func addLongPressGesture(target target: AnyObject, action: Selector) {
let longPress = UILongPressGestureRecognizer(target: target, action: action)
addGestureRecognizer(longPress)
userInteractionEnabled = true
}
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Transform
/* --------------------------------------------------------------------------- */
/**
Set Rotation **X**
- parameter x: CGFloat
*/
public func setRotationX(x: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.toDegreesToRadians, 1.0, 0.0, 0.0)
self.layer.transform = transform
}
/**
Set Rotation **Y**
- parameter y: CGFloat
*/
public func setRotationY(y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, y.toDegreesToRadians, 0.0, 1.0, 0.0)
self.layer.transform = transform
}
/**
Set Rotation **Z**
- parameter z: CGFloat
*/
public func setRotationZ(z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, y.toDegreesToRadians, 0.0, 0.0, 1.0)
self.layer.transform = transform
}
/**
Set rotation **X, Y, Z**
- parameter x: CGFloat
- parameter y: CGFloat
- parameter z: CGFloat
*/
public func setRotation(x x: CGFloat, y: CGFloat, z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.toDegreesToRadians, 1.0, 0.0, 0.0)
transform = CATransform3DRotate(transform, y.toDegreesToRadians, 0.0, 1.0, 0.0)
transform = CATransform3DRotate(transform, z.toDegreesToRadians, 0.0, 0.0, 1.0)
self.layer.transform = transform
}
/**
Set Scale
- parameter x: CGFloat
- parameter y: CGFloat
*/
public func setScale(x x: CGFloat, y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, x, y, 1)
self.layer.transform = transform
}
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Layer
/* --------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Layer / Border, Corner
/* --------------------------------------------------------------------------- */
/**
Set Rounder
- parameter radius: CGFloat
*/
public func addRounder(radius:CGFloat) {
self.layer.cornerRadius = radius
self.clipsToBounds = true
}
/**
Set Round
*/
public func addRound() {
self.layer.cornerRadius = self.width / 2
self.clipsToBounds = true
}
/**
Round cornerd on UIView by enum UIRectCorner with radius
- parameter corners: UIRectCorner / .TopLeft, .TopRight, .BottomLeft, .BottomRight, .AllCorners
- parameter radius: CGFloat
*/
public func addRoundCorners(corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
self.layer.mask = mask
}
/**
Add border
- parameter width: CGFloat
- parameter color: UIColor
*/
public func addBorder(width width: CGFloat, color: UIColor) {
self.layer.borderWidth = width
self.layer.borderColor = color.CGColor
self.layer.masksToBounds = true
}
/**
Add Border Top
- parameter size: CGFloat
- parameter color: UIColor
*/
public func addBorderTop(size size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
}
/**
Add Border Bottom
- parameter size: CGFloat
- parameter color: UIColor
*/
public func addBorderBottom(size size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
}
/**
Add Border Left
- parameter size: CGFloat
- parameter color: UIColor
*/
public func addBorderLeft(size size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
}
/**
Add Border Right
- parameter size: CGFloat
- parameter color: UIColor
*/
public func addBorderRight(size size: CGFloat, color: UIColor) {
addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
}
/**
add border utility private
- parameter x: CGFloat
- parameter y: CGFloat
- parameter width: CGFloat
- parameter height: CGFloat
- parameter color: UIColor
*/
private func addBorderUtility(x x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRect(x: x, y: y, width: width, height: height)
layer.addSublayer(border)
}
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Layer / Draw
/* --------------------------------------------------------------------------- */
/**
Draw Circle
- parameter fillColor: UIColor
- parameter strokeColor: UIColor
- parameter strokeWidth: CGFloat
*/
public func drawCircle(fillColor fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = fillColor.CGColor
shapeLayer.strokeColor = strokeColor.CGColor
shapeLayer.lineWidth = strokeWidth
self.layer.addSublayer(shapeLayer)
}
/**
Draw Stroke
- parameter width: CGFloat
- parameter color: UIColor
*/
public func drawStroke(width width: CGFloat, color: UIColor) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.width, height: self.width), cornerRadius: self.width/2)
let shapeLayer = CAShapeLayer ()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = color.CGColor
shapeLayer.lineWidth = width
self.layer.addSublayer(shapeLayer)
}
/* --------------------------------------------------------------------------- */
// MARK: - UIView → Layer / Shadow
/* --------------------------------------------------------------------------- */
/**
Apply Shadow
- parameter offset: CGSize
- parameter radius: CGFloat
- parameter color: UIColor
- parameter opacity: Float
- parameter cornerRadius: CGFloat?
*/
public func addShadow(offset offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.shadowColor = color.CGColor
if let r = cornerRadius {
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).CGPath
}
}
/**
Plain Shadow
<img src="http://yannickstephan.com/easyhelper/shadow1.png" height="200" width="200"/>
- parameter shadowColor: UIColor ( default = UIColor.blackColor() )
- parameter shadowOpacity: Float ( default = 0.4 )
- parameter shadowRadius: CGFloat ( default = 0.5 )
- parameter shadowOffset: CGSize ( default = CGSize(width: 0, height: 10) )
*/
public func addPlainShadow(
shadowColor:UIColor = UIColor.blackColor(),
shadowOpacity:Float = 0.4,
shadowRadius:CGFloat = 5,
shadowOffset:CGSize = CGSize(width: 0, height: 10)) {
self.layer.shadowColor = shadowColor.CGColor
self.layer.shadowOffset = shadowOffset
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowRadius = shadowRadius
}
/**
Curved Shadow
<img src="http://yannickstephan.com/easyhelper/shadow1.png" height="200" width="200"/>
- parameter shadowOpacity: Float ( default = 0.3 )
- parameter shadowOffset: CGSize ( default = CGSize(width: 0, height: -3) )
- parameter shadowColor: UIColor ( default = UIColor.blackColor() )
- parameter depth: CGFloat ( default = 11.0 )
- parameter lessDepth: CGFloat ( default = 0.8 )
- parameter curviness: CGFloat ( default = 5 )
- parameter radius: CGFloat ( default = 1 )
*/
public func addCurvedShadow(
shadowOpacity shadowOpacity:Float = 0.3,
shadowOffset:CGSize = CGSize(width: 0, height: -3),
shadowColor:UIColor = UIColor.blackColor(),
depth:CGFloat = 11.00 ,
lessDepth:CGFloat = 0.8,
curviness:CGFloat = 5,
radius:CGFloat = 1 ) {
let path = UIBezierPath()
// top left
path.moveToPoint(CGPoint(x: radius, y: self.height))
// top right
path.addLineToPoint(CGPoint(x: self.width - 2 * radius, y: self.height))
// bottom right + a little extra
path.addLineToPoint(CGPoint(x: self.width - 2 * radius, y: self.height + depth))
// path to bottom left via curve
path.addCurveToPoint(
CGPoint(x: radius, y: self.height + depth),
controlPoint1: CGPoint(
x: self.width - curviness,
y: self.height + (lessDepth * depth) - curviness),
controlPoint2: CGPoint(
x: curviness,
y: self.height + (lessDepth * depth) - curviness))
self.layer.shadowPath = path.CGPath
self.layer.shadowColor = shadowColor.CGColor
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowRadius = radius
self.layer.shadowOffset = shadowOffset
}
/**
Hover Shadow
<img src="http://yannickstephan.com/easyhelper/shadow1.png" height="200" width="200"/>
*/
public func addHoverShadow() {
let path = UIBezierPath(roundedRect: CGRect(x: 5, y: self.height + 5, width: self.width - 10, height: 15), cornerRadius: 10)
self.layer.shadowPath = path.CGPath
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 5
self.layer.shadowOffset = CGSize(width: 0, height: 0)
}
/**
Flat shadow
<img src="http://yannickstephan.com/easyhelper/flatshadow.png" height="100" width="100"/>
*/
public func addFlatShadow(){
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0.0, 2.0)
self.layer.masksToBounds = false
self.layer.shadowRadius = 1.0
self.layer.shadowOpacity = 0.5
}
/* --------------------------------------------------------------------------- */
// MARK: - Animate
/* --------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------- */
// MARK: - Animate / Stop Start
/* --------------------------------------------------------------------------- */
/**
Stop current animation
*/
public func stopAnimation() {
CATransaction.begin()
self.layer.removeAllAnimations()
CATransaction.commit()
CATransaction.flush()
}
/**
Is view is being animates
- returns: Bool
*/
public func isBeingAnimated() -> Bool {
return self.layer.animationKeys()?.count > 0
}
/* --------------------------------------------------------------------------- */
// MARK: - Animate / FadIn Out
/* --------------------------------------------------------------------------- */
/**
Fade In
- parameter duration: NSTimeInterval ( default = 1.0 )
- parameter delay: NSTimeInterval ( default = 0 )
- parameter alpha: CGFloat ( default = 1.0 )
- parameter completionEnd: (() -> ())? When animation is finished
*/
public func applyFadeIn(
duration duration: NSTimeInterval = 1.0,
delay: NSTimeInterval = 0.0,
toAlpha: CGFloat = 1,
completionEnd: ((Bool) -> ())? = nil) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: {
self.alpha = toAlpha
}, completion: completionEnd)
/*
let animation = CABasicAnimation(keyPath:"opacity")
animation.beginTime = CACurrentMediaTime() + delay;
animation.duration = duration
animation.fromValue = 0
animation.toValue = alpha
animation.fillMode = kCAFillModeBoth
CATransaction.setCompletionBlock(completionEnd)
self.layer.addAnimation(animation, forKey:"animateOpacity")*/
}
/**
Fade Out
- parameter duration: NSTimeInterval ( default = 1.0 )
- parameter delay: NSTimeInterval ( default = 0.0 )
- parameter alpha: CGFloat ( default = 0 )
- parameter completionEnd: (() -> ())? When animation is finished
*/
public func applyFadeOut(
duration duration: NSTimeInterval = 1.0,
delay: NSTimeInterval = 0.0,
toAlpha: CGFloat = 0,
completionEnd: ((Bool) -> ())? = nil) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: {
self.alpha = toAlpha
}, completion: completionEnd)
/* let animation = CABasicAnimation(keyPath:"opacity")
animation.beginTime = CACurrentMediaTime() + delay;
animation.duration = duration
animation.fromValue = 1
animation.toValue = alpha
animation.fillMode = kCAFillModeBoth
CATransaction.setCompletionBlock(completionEnd)
self.layer.addAnimation(animation, forKey:"animateOpacity")*/
}
/* --------------------------------------------------------------------------- */
// MARK: - Animate / Shake
/* --------------------------------------------------------------------------- */
/**
Shake Horizontally
- parameter duration: duration ( default = 0.5 )
- parameter moveValues: moveValues ( default = [-12, 12, -8, 8, -4, 4, 0] )
- parameter completionEnd: (() -> ())? When animation is finished
*/
public func applyShakeHorizontally(
duration duration:CFTimeInterval = 0.5,
moveValues:[Float] = [-12, 12, -8, 8, -4, 4, 0],
completionEnd: dispatch_block_t? = nil) {
let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.values = moveValues
CATransaction.setCompletionBlock(completionEnd)
self.layer.addAnimation(animation, forKey: "shake")
}
/**
Shake Vertically
- parameter duration: duration ( default = 0.5 )
- parameter moveValues: moveValues ( default = [-12, 12, -8, 8, -4, 4, 0] )
- parameter completionEnd: (() -> ())? When animation is finished
*/
public func applyShakeVertically(
duration duration:CFTimeInterval = 0.5,
moveValues:[Float] = [(-12), (12), (-8), (8), (-4), (4), (0) ],
completionEnd: (() -> ())) {
let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.values = moveValues
CATransaction.setCompletionBlock(completionEnd)
self.layer.addAnimation(animation, forKey: "shake")
}
/* --------------------------------------------------------------------------- */
// MARK: - Animate / Rotate
/* --------------------------------------------------------------------------- */
/**
Set Animation Rotation on View
- parameter angle: CGFloat ( example 360 = 360 degrees)
- parameter duration: NSTimeInterval
- parameter direction: UIViewContentMode ( .Left, .Right )
- parameter repeatCount: Float
- parameter autoReverse: Bool
- parameter completionEnd: (() -> ())? When animation is finished
*/
public func applyRotateToAngle(
angle:CGFloat,
duration:NSTimeInterval,
direction:UIViewContentMode,
repeatCount:Float = 0,
autoReverse:Bool = false,
completionEnd: dispatch_block_t? = nil
) {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = (direction == UIViewContentMode.Right ? angle.toDegreesToRadians : -angle.toDegreesToRadians)
rotationAnimation.duration = duration
rotationAnimation.autoreverses = autoReverse
rotationAnimation.repeatCount = repeatCount
rotationAnimation.removedOnCompletion = false
rotationAnimation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionLinear)
CATransaction.setCompletionBlock(completionEnd)
self.layer.addAnimation(rotationAnimation,forKey:"transform.rotation.z")
}
/**
Set animation Pulse on View
- parameter toScale: CGFloat
- parameter duration: NSTimeInterval
- parameter repeatAnimate: Bool
- parameter completionEnd: (() -> ())? When animation is finished
*/
public func applyPulseToSize(
duration duration:NSTimeInterval,
toScale:CGFloat,
repeatAnimate:Bool,
completionEnd: dispatch_block_t? = nil
) {
let pulseAnimate = CABasicAnimation(keyPath: "transform.scale")
pulseAnimate.duration = duration
pulseAnimate.toValue = toScale
pulseAnimate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pulseAnimate.autoreverses = true
pulseAnimate.repeatCount = repeatAnimate ? Float.infinity : 0
CATransaction.setCompletionBlock(completionEnd)
self.layer.addAnimation(pulseAnimate, forKey:"pulse")
}
@available(iOS 7,*)
/**
Motion Effects
- parameter minimumRelativeValueX: Min Relative Value X ( default = -10.00 )
- parameter maximumRelativeValueX: Max Relative Value X ( default = 10.00 )
- parameter minimumRelativeValueY: Min Relative Value Y ( default = -10.00 )
- parameter maximumRelativeValueY: Max Relative Value Y ( default = 10.00 )
*/
public func applyMotionEffects(
minimumRelativeValueX:Float = -10.00,
maximumRelativeValueX:Float = 10.00,
minimumRelativeValueY:Float = -10.00,
maximumRelativeValueY:Float = 10.00
) {
let horizontalEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type:.TiltAlongHorizontalAxis)
horizontalEffect.minimumRelativeValue = minimumRelativeValueX
horizontalEffect.maximumRelativeValue = maximumRelativeValueX
let verticalEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
verticalEffect.minimumRelativeValue = minimumRelativeValueY
verticalEffect.maximumRelativeValue = maximumRelativeValueY
let motionEffectGroup = UIMotionEffectGroup()
motionEffectGroup.motionEffects = [horizontalEffect, verticalEffect]
self.addMotionEffect(motionEffectGroup)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment