Skip to content

UIKit & Foundation toolbelt for quick prototyping and rapid development

License

Notifications You must be signed in to change notification settings

JuanPabloBoero/CEMKit-Swift

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CEMKit

UIKit & Foundation toolbelt for quick prototyping and rapid development.

Table of Contents

Installation

Manual

Copy & Paste CEMKit.swift into your project

Cocoapods

pod "CEMKit-Swift", "~> 0.1.5"

Documentation

UIView extension

Init

Quick init method for views
    convenience init (x: CGFloat,
        y: CGFloat,
        w: CGFloat,
        h: CGFloat)

Frame

Get/Set frame values
    var x: CGFloat {
        get {
            return self.frame.origin.x
        } set (value) {
            self.frame = CGRect (x: value, y: self.y, width: self.w, height: self.h)
        }
    }
    var y: CGFloat {
        get {
            return self.frame.origin.y
        } set (value) {
            self.frame = CGRect (x: self.x, y: value, width: self.w, height: self.h)
        }
    }
    var w: CGFloat {
        get {
            return self.frame.size.width
        } set (value) {
            self.frame = CGRect (x: self.x, y: self.y, width: value, height: self.h)
        }
    }
    var h: CGFloat {
        get {
            return self.frame.size.height
        } set (value) {
            self.frame = CGRect (x: self.x, y: self.y, width: self.w, height: value)
        }
    }
    var position: CGPoint {
        get {
            return self.frame.origin
        } set (value) {
            self.frame = CGRect (origin: value, size: self.frame.size)
        }
    }
    var size: CGSize {
        get {
            return self.frame.size
        } set (value) {
            self.frame = CGRect (origin: self.frame.origin, size: size)
        }
    }
Logical frame properties
    var left: CGFloat {
        get {
            return self.x
        } set (value) {
            self.x = value
        }
    }
    var right: CGFloat {
        get {
            return self.x + self.w
        } set (value) {
            self.x = value - self.w
        }
    }
    var top: CGFloat {
        get {
            return self.y
        } set (value) {
            self.y = value
        }
    }
    var bottom: CGFloat {
        get {
            return self.y + self.h
        } set (value) {
            self.y = value - self.h
        }
    }
Get logical frame values with offset
	func leftWithOffset (offset: CGFloat) -> CGFloat
	func rightWithOffset (offset: CGFloat) -> CGFloat
	func topWithOffset (offset: CGFloat) -> CGFloat
	func botttomWithOffset (offset: CGFloat) -> CGFloat

Layer

Setting anchor position easily
	enum AnchorPosition: CGPoint {
	    case TopLeft        = "{0, 0}"
	    case TopCenter      = "{0.5, 0}"
	    case TopRight       = "{1, 0}"
	    
	    case MidLeft        = "{0, 0.5}"
	    case MidCenter      = "{0.5, 0.5}"
	    case MidRight       = "{1, 0.5}"
	    
	    case BottomLeft     = "{0, 1}"
	    case BottomCenter   = "{0.5, 1}"
	    case BottomRight    = "{1, 1}"
	}
    func setAnchorPosition (anchorPosition: AnchorPosition)
Shadow, Border, Corner Radius, Stroke, Circle

Adding shadow

    
    func addShadow (
        offset: CGSize,
        radius: CGFloat,
        color: UIColor,
        opacity: Float,
        cornerRadius: CGFloat? = nil,
        shouldRasterize: Bool)    

Adding borders

    func addBorder (width: CGFloat,
        color: UIColor)

Setting corner radius of borders

    func setCornerRadius (radius: CGFloat)

Adding stroke to borders

    func drawStroke (width: CGFloat,
        color: UIColor)

Circle Drawing

    func drawCircle (fillColor: UIColor,
        strokeColor: UIColor,
        strokeWidth: CGFloat)

Arc Drawing

    func drawArc (from: CGFloat,
        to: CGFloat,
        clockwise: Bool,
        width: CGFloat,
        fillColor: UIColor,
        strokeColor: UIColor,
        lineCap: String)

Transform

Set rotation
	func setRotationX (x: CGFloat)
	func setRotationY (y: CGFloat)
	func setRotationZ (z: CGFloat)
    
   func setRotation (x: CGFloat,
   		y: CGFloat,
   		z: CGFloat)
Set scale
    func setScale (x: CGFloat,
        y: CGFloat)

Animation

Animating view with constant values

Constants

	let UIViewAnimationDuration: NSTimeInterval = 1
	let UIViewAnimationSpringDamping: CGFloat = 0.5
	let UIViewAnimationSpringVelocity: CGFloat = 0.5

Animation Mehtods

    func animate (animations: (()->Void)!,
        completion: ((Bool)->Void)? = nil) 
        
    func spring (animations: (()->Void)!,
        completion: ((Bool)->Void)? = nil)

Rendering

Get UIImage form view

	func toImage () -> UIImage

Gestures

Adding gestures single line

Tap

    func addTapGesture (tapNumber: NSInteger,
        target: AnyObject, action: Selector)
	func addTapGesture (tapNumber: Int,
	        action: ((UITapGestureRecognizer)->())?)

Swipe

    func addSwipeGesture (
    	direction: UISwipeGestureRecognizerDirection,  
        numberOfTouches: Int,  
        target: AnyObject,  
        action: Selector)  
	func addSwipeGesture (direction: UISwipeGestureRecognizerDirection,
	        numberOfTouches: Int,
	        action: ((UISwipeGestureRecognizer)->())?)

Pan

    func addPanGesture (target: AnyObject,
        action: Selector)
	func addPanGesture (action: ((UIPanGestureRecognizer)->())?)

Pinch

	func addPinchGesture (target: AnyObject,
	        action: Selector)
	func addPinchGesture (action: ((UIPinchGestureRecognizer)->())?)

Long Press

	func addLongPressGesture (target: AnyObject,
	        action: Selector)
	func addLongPressGesture (action: ((UILongPressGestureRecognizer)->())?)

UIViewController extension

Get top layout and bottom layout

Top

    var top: CGFloat {
        get {
            if let nav = self.navigationController {
                if nav.navigationBarHidden {
                    return view.top
                } else {
                    return nav.navigationBar.bottom
                }
            } else {
                return view.top
            }
        }
    }

Bottom

    var bottom: CGFloat {
        get {
            if let tab = tabBarController {
                if tab.tabBar.hidden {
                    return view.bottom
                } else {
                    return tab.tabBar.top
                }
            } else {
                return view.bottom
            }
        }
    }
Calculate app area exluding NavigationBar and TabBar
    var applicationFrame: CGRect {
        get {
            return CGRect (x: view.x, y: top, width: view.w, height: bottom - top)
        }
    }
Quick access tab bar properties
    var tabBarHeight: CGFloat {
        get {
            if let tab = self.tabBarController {
                return tab.tabBar.frame.size.height
            }
            
            return 0
        }
    }
Quick access navigation bar properties
	 var navBar: UINavigationBar? {
        get {
            return navigationController?.navigationBar
        }
    }

Get Navigation bar height of device

    var navigationBarHeight: CGFloat {
        get {
            if let nav = self.navigationController {
                return nav.navigationBar.h
            }
            
            return 0
        }
    }

Get or set navigation bar color

    var navigationBarColor: UIColor? {
        get {
            return navigationController?.navigationBar.tintColor
        } set (value) {
            navigationController?.navigationBar.barTintColor = value
        }
    }

Push view controller

    func push (vc: UIViewController) {
        navigationController?.pushViewController(vc, animated: true)
    }

Pop view controller

    func pop () {
        navigationController?.popViewControllerAnimated(true)
    }

Present view controller

	func present (vc: UIViewController)

Dismiss view controller

	func dismiss (completion: (()->Void)?) 

UIScrollView extension

Get/Set ContentSize Properties
    var contentHeight: CGFloat {
        get {
            return contentSize.height
        } set (value) {
            contentSize = CGSize (width: contentSize.width, height: value)
        }
    }
    var contentWidth: CGFloat {
        get {
            return contentSize.height
        } set (value) {
            contentSize = CGSize (width: value, height: contentSize.height)
        }
    }
Get/Set ContentOffset Properties
    var offsetX: CGFloat {
        get {
            return contentOffset.x
        } set (value) {
            contentOffset = CGPoint (x: value, y: contentOffset.y)
        }
    }
    var offsetY: CGFloat {
        get {
            return contentOffset.y
        } set (value) {
            contentOffset = CGPoint (x: contentOffset.x, y: value)
        }
    }

UILabel extension

NSAttributedString

AttributedStrings property for accessing, adding or updating attributedText of label
	private var UILabelAttributedStringArray: UInt8 = 0
    var attributedStrings: [NSAttributedString]? {
        get {
            return objc_getAssociatedObject(self, &UILabelAttributedStringArray) as? [NSAttributedString]
        } set (value) {
            objc_setAssociatedObject(self, &UILabelAttributedStringArray, value, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
        }
    }

Adding

    func addAttributedString (text: String,
        color: UIColor,
        font: UIFont)
    func addAttributedString (attributedString: NSAttributedString)

Updating

    func updateAttributedStringAtIndex (index: Int,
        attributedString: NSAttributedString)
    func updateAttributedStringAtIndex (index: Int,
        newText: String)

Self sizing

Get estimated frame values for current state
	 func getEstimatedRect (width: CGFloat = CGFloat.max, height: CGFloat = CGFloat.max) -> CGRect
	 func getEstimatedHeight () -> CGFloat
	 func getEstimatedWidth () -> CGFloat
Fix frame for current state
	func fitHeight ()
	func fitWidth ()
	func fitSize ()

Initilizers

Init with Text, TextColor, TextAlignment & Font
	    convenience init (
        frame: CGRect,
        text: String,
        textColor: UIColor,
        textAlignment: NSTextAlignment,
        font: UIFont)
	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        width: CGFloat,
	        height: CGFloat,
	        text: String,
	        textColor: UIColor,
	        textAlignment: NSTextAlignment,
	        font: UIFont)

Auto calculates height

	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        width: CGFloat,
	        text: String,
	        textColor: UIColor,
	        textAlignment: NSTextAlignment,
	        font: UIFont)

Auto calculates height with giving padding

	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        width: CGFloat,
	        padding: CGFloat,
	        text: String,
	        textColor: UIColor,
	        textAlignment: NSTextAlignment,
	        font: UIFont)

Auto calculates frame

	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        text: String,
	        textColor: UIColor,
	        textAlignment: NSTextAlignment,
	        font: UIFont)
Init with AttributedText
    convenience init (
        frame: CGRect,
        attributedText: NSAttributedString,
        textAlignment: NSTextAlignment)
	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        width: CGFloat,
	        height: CGFloat,
	        attributedText: NSAttributedString,
	        textAlignment: NSTextAlignment) 

Auto calculates height

	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        width: CGFloat,
	        attributedText: NSAttributedString,
	        textAlignment: NSTextAlignment)

Auto calculates frame

	convenience init (
	        x: CGFloat,
	        y: CGFloat,
	        attributedText: NSAttributedString,
	        textAlignment: NSTextAlignment)

NSAttributedString

NSAttributedStringStyle enum

Easy styling

    enum NSAttributedStringStyle {
        case plain
        case underline (NSUnderlineStyle, UIColor)
        case strike (UIColor, CGFloat)
     }
	func addAtt (attribute: [NSString: NSObject]) -> NSAttributedString
	func addStyle (style: NSAttributedStringStyle) -> NSAttributedString

Easy Init

    convenience init (text: String,
        color: UIColor,
        font: UIFont,
        style: NSAttributedStringStyle = .plain)
	convenience init (image: UIImage)

Create multiple NSAttributeString with closures

	class func withAttributedStrings (mutableString: (NSMutableAttributedString)->()) -> NSAttributedString

Example:

   let att = NSAttributedString.withAttributedStrings({ att in
       att.appendAttributedString (NSAttributedString(
           text: "asd",
           color: UIColor.blackColor(),
           font: UIFont.systemFontOfSize(22)))
       att.appendAttributedString (NSAttributedString(
           text: "\nasd",
           color: UIColor.blueColor(),
           font: UIFont.systemFontOfSize(15)))
       att.appendAttributedString (NSAttributedString(
           text: "\nasdjnfje",
           color: UIColor.redColor(),
           font: UIFont.systemFontOfSize(25)))
       att.appendAttributedString (NSAttributedString(
           text: "\nasd",
           color: UIColor.blackColor(),
           font: UIFont.Font(.AvenirNext,
               type: UIFont.FontType.DemiBold,
               size: 15),
           style: .underline(.StyleSingle, UIColor.blueColor())))
   })

String extension

Subscript for accessing characters at index of string
    subscript (i: Int) -> String {
        return String(Array(self)[i])
    }

UIFont extension

FontType and FontName enums for easily create UIFonts
	enum FontType: String
	enum FontName: String
	class func Font (name: FontName, type: FontType, size: CGFloat) -> UIFont

Even customise it for specific font

    class func HelveticaNeue (type: FontType, size: CGFloat) -> UIFont

Print all family of font on single line

    class func PrintFontFamily (font: FontName)

UIImageView

Init with image

    convenience init (frame: CGRect,
        imageName: String)
    convenience init (frame: CGRect,
        image: UIImage)

Init with aspected image

    convenience init (
			x: CGFloat,
			y: CGFloat,
			width: CGFloat,
			image: UIImage)
	convenience init (
			x: CGFloat,
	      	y: CGFloat,
	      	height: CGFloat,
	      	image: UIImage)

Download image background

	func imageWithUrl (url: String)

With placeholder image

	func imageWithUrl (url: String, placeholder: UIImage)

With placeholder image named

	func imageWithUrl (url: String, placeholder: String)

UIColor extension

Create random color or RGB/A colors easily in range of [0, 255]
    class func randomColor () -> UIColor
    class func RGBColor (r: CGFloat,
        g: CGFloat,
        b: CGFloat) -> UIColor
    class func RGBAColor (r: CGFloat,
        g: CGFloat,
        b: CGFloat,
        a: CGFloat) -> UIColor
	class func Gray (gray: CGFloat) -> UIColor
	class func Gray (gray: CGFloat, alpha: CGFloat) -> UIColor
	class func HexColor (hex: String) -> UIColor

UIImage extension

Resize an image with keep it aspect ratio

Calculate possible aspect width for height

    func aspectWidthForHeight (height: CGFloat) -> CGFloat

Calculate possible aspect height for width

	func aspectHeightForWidth (width: CGFloat) -> CGFloat

Resize image based on its width (auto calculates height and keeps aspect ratio)

    func aspectResizeWithWidth (width: CGFloat) -> UIImage

Resize image based on its height (auto calculates width and keeps aspect ratio)

    func aspectResizeWithHeight (height: CGFloat) -> UIImage

NSDate

Easy convert to string with format
    func toString (format: String) -> String {
        let formatter = NSDateFormatter ()
        formatter.dateFormat = format
        
        return formatter.stringFromDate(self)
    }

Array

Remove Object
	mutating func removeObject<U: Equatable> (object: U)

Dictionary

Add operator
	func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>,
	    right: Dictionary<KeyType, ValueType>)

Dispatch

dispatch_after function
	func delay (
	    seconds: Double,
	    queue: dispatch_queue_t = dispatch_get_main_queue(),
	    after: ()->()) {
	        
	        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
	        dispatch_after(time, queue, after)
	}

Download Tasks

Request url string

	func urlRequest (
	    url: String,
	    success: (NSData?)->Void,
	    error: ((NSError)->Void)? = nil)

Request image

	func imageRequest (
	    url: String,
	    success: (UIImage?)->Void)

Request json

	func jsonRequest (
	    url: String,
	    success: (AnyObject?->Void),
	    error: ((NSError)->Void)?) 

NSData to json serialized AnyObject?
(could be [AnyObject], [String: AnyObject], nil)

	func dataToJsonDict (data: NSData?) -> AnyObject? 

UIScreen

Access device related mesurements

Orientation

	var Orientation: UIInterfaceOrientation {
	    get {
	        return UIApplication.sharedApplication().statusBarOrientation
	    }
	}

Screen Width

	var ScreenWidth: CGFloat {
	    get {
	        if UIInterfaceOrientationIsPortrait(Orientation) {
	            return UIScreen.mainScreen().bounds.size.width
	        } else {
	            return UIScreen.mainScreen().bounds.size.height
	        }
	    }
	}

Screen Height

	var ScreenHeight: CGFloat {
	    get {
	        if UIInterfaceOrientationIsPortrait(Orientation) {
	            return UIScreen.mainScreen().bounds.size.height
	        } else {
	            return UIScreen.mainScreen().bounds.size.width
	        }
	    }
	}

Status bar height

	var StatusBarHeight: CGFloat {
	    get {
	        return UIApplication.sharedApplication().statusBarFrame.height
	    }
	}

CGPoint

Custom operators for CGPoints
	func + (left: CGPoint, right: CGPoint) -> CGPoint
	func - (left: CGPoint, right: CGPoint) -> CGPoint
StringLiteralConvertable implementation
	public init(stringLiteral value: StringLiteralType)
	public init(extendedGraphemeClusterLiteral value: StringLiteralType)
	public init(unicodeScalarLiteral value: StringLiteralType) {
	        self = CGPointFromString(value)

CGSize

Custom operators for CGSizes
	func + (left: CGSize, right: CGSize) -> CGSize
	func - (left: CGSize, right: CGSize) -> CGSize

CGFloat

Convert degrees to radians
	func degreesToRadians (angle: CGFloat) -> CGFloat
Normalize value to [0, 1] or vice verca

Convert [min, max] to [0, 1]

	func normalizeValue (
		value: CGFloat,
	    min: CGFloat,
	    max: CGFloat) -> CGFloat

Convert [0, 1] to to [min, max]

	func convertNormalizedValue (
		value: CGFloat,
	    min: CGFloat,
	    max: CGFloat) -> CGFloat
Clamp a value between minimum and maximum values
	func clamp (
	    value: CGFloat,
	    minimum: CGFloat,
	    maximum: CGFloat) -> CGFloat
Calculate aspected height of wanted target aspect width by current width & height
	func aspectHeightForTargetAspectWidth (
	    currentHeight: CGFloat,
	    currentWidth: CGFloat,
	    targetAspectWidth: CGFloat) -> CGFloat 
Calculate aspected width of wanted target aspect height by current width & height
	func aspectWidthForTargetAspectHeight (
	    currentHeight: CGFloat,
	    currentWidth: CGFloat,
	    targetAspectHeight: CGFloat) -> CGFloat

UIAlertViewController

Single line, block based ios 8 alert
	func alert (title: String,
	    message: String,
	    cancelAction: ((UIAlertAction!)->Void)? = nil,
	    okAction: ((UIAlertAction!)->Void)? = nil) -> UIAlertController
Action sheet
	func actionSheet (
	    title: String,
	    message: String,
	    actions: [UIAlertAction]) -> UIAlertController

UIBarButtonItem

Create bar button item with image, single line
	func barButtonItem (
		imageName: String,
	    size: CGFloat,
	    action: (AnyObject)->())
	func barButtonItem (
		imageName: String,
	    action: (AnyObject)->()) -> UIBarButtonItem

Create bar button item with text and color

	func barButtonItem (
		title: String,
	    color: UIColor,
	    action: (AnyObject)->()) -> UIBarButtonItem

BlockButton

Regular UIButton with actionBlock:
    var actionBlock: ((sender: BlockButton) -> ())? {
        didSet {
            self.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
        }
    }
    
    func action (sender: BlockButton) {
        actionBlock! (sender: sender)
    }

BlockWebView

Regular UIWebView with block based actions instead of UIWebViewDelegate
    var didStartLoad: ((NSURLRequest) -> ())?
    var didFinishLoad: ((NSURLRequest) -> ())?
    var didFailLoad: ((NSURLRequest, NSError) -> ())?    
    var shouldStartLoadingRequest: ((NSURLRequest) -> (Bool))?

BlockTap

Regular UITapGestureRecognizer with block based action
	init (tapCount: Int,
	        fingerCount: Int,
	        action: ((UITapGestureRecognizer)->())?)

BlockPan

Regular UIPanGestureRecognizer with block based action
	init (action: ((UIPanGestureRecognizer)->())?)

BlockSwipe

Regular UISwipeGestureRecognizer with block based action
	init (direction: UISwipeGestureRecognizerDirection,
	        fingerCount: Int,
	        action: ((UISwipeGestureRecognizer)->())?)

BlockPinch

Regular UIPinchGestureRecognizer with block based action
	init (action: ((UIPinchGestureRecognizer)->())?)

BlockLongPress

Regular UILongPressGestureRecognizer with block based action
	init (action: ((UILongPressGestureRecognizer)->())?)

About

UIKit & Foundation toolbelt for quick prototyping and rapid development

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 92.1%
  • Ruby 7.9%