Merging from upatream

This commit is contained in:
Valentino Urbano 2016-02-27 16:41:50 +01:00
commit 23f9eae7ec
19 changed files with 406 additions and 139 deletions

View File

@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "EZSwiftExtensions"
s.version = "1.1.1"
s.version = "1.2"
s.summary = ":smirk: How Swift standard types and classes were supposed to work"
s.description = ":smirk: How Swift standard types and classes were supposed to work."
s.homepage = "https://github.com/goktugyil/EZSwiftExtensions"

View File

@ -15,11 +15,16 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0.2</string>
<string>1.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSPrincipalClass</key>
<string></string>
<key>UILaunchStoryboardName</key>
@ -28,10 +33,5 @@
<string>Main</string>
<key>UIRequiresFullScreen</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>

View File

@ -0,0 +1,51 @@
//
// NSAttributedStringExtensions.swift
// EZSwiftExtensions
//
// Created by Lucas Farah on 18/02/16.
// Copyright (c) 2016 Lucas Farah. All rights reserved.
//
import UIKit
extension NSAttributedString {
/// EZSE: Adds bold attribute to NSAttributedString and returns it
func bold() -> NSAttributedString {
let copy = self.mutableCopy()
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())], range: range)
return copy as! NSAttributedString
}
/// EZSE: Adds underline attribute to NSAttributedString and returns it
func underline() -> NSAttributedString {
let copy = self.mutableCopy()
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue], range: range)
return copy as! NSAttributedString
}
/// EZSE: Adds italic attribute to NSAttributedString and returns it
func italic() -> NSAttributedString {
let copy = self.mutableCopy()
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())], range: range)
return copy as! NSAttributedString
}
/// EZSE: Adds color attribute to NSAttributedString and returns it
func color(color: UIColor) -> NSAttributedString {
let copy = self.mutableCopy()
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSForegroundColorAttributeName: color], range: range)
return copy as! NSAttributedString
}
}
/// EZSE: Appends one NSAttributedString to another NSAttributedString and returns it
public func += (inout left: NSAttributedString, right: NSAttributedString) {
let ns = NSMutableAttributedString(attributedString: left)
ns.appendAttributedString(right)
left = ns
}

View File

@ -0,0 +1,33 @@
//
// NSTimerExtensions.swift
// EZSwiftExtensions
//
// Created by Lucas Farah on 15/07/15.
// Copyright (c) 2016 Lucas Farah. All rights reserved.
//
import UIKit
extension NSTimer {
/// EZSE: Runs every x seconds, to cancel use: timer.invalidate()
public static func runThisEvery(seconds seconds: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
/// EZSE: Run function after x seconds
public static func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
runThisAfterDelay(seconds: seconds, queue: dispatch_get_main_queue(), after: after)
}
//TODO: Make this easier
/// EZSwiftExtensions - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
public static func runThisAfterDelay(seconds seconds: Double, queue: dispatch_queue_t, after: ()->()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, queue, after)
}
}

View File

@ -41,6 +41,8 @@
E1839E371BF79974002212C6 /* UITextViewExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1839E1B1BF79974002212C6 /* UITextViewExtensions.swift */; };
E1839E381BF79974002212C6 /* UIViewControllerExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1839E1C1BF79974002212C6 /* UIViewControllerExtensions.swift */; };
E1839E391BF79974002212C6 /* UIViewExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1839E1D1BF79974002212C6 /* UIViewExtensions.swift */; };
E197F7BD1C7FCE9D00FC6144 /* NSTimerExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E197F7BC1C7FCE9D00FC6144 /* NSTimerExtensions.swift */; };
E197F7BF1C7FD8C500FC6144 /* NSAttributedStringExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E197F7BE1C7FD8C500FC6144 /* NSAttributedStringExtensions.swift */; };
E1CB3C1C1C25FFA000DF77CD /* DoubleExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1CB3C1B1C25FFA000DF77CD /* DoubleExtensions.swift */; };
/* End PBXBuildFile section */
@ -81,6 +83,8 @@
E1839E1B1BF79974002212C6 /* UITextViewExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UITextViewExtensions.swift; path = Sources/UITextViewExtensions.swift; sourceTree = SOURCE_ROOT; };
E1839E1C1BF79974002212C6 /* UIViewControllerExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UIViewControllerExtensions.swift; path = Sources/UIViewControllerExtensions.swift; sourceTree = SOURCE_ROOT; };
E1839E1D1BF79974002212C6 /* UIViewExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UIViewExtensions.swift; path = Sources/UIViewExtensions.swift; sourceTree = SOURCE_ROOT; };
E197F7BC1C7FCE9D00FC6144 /* NSTimerExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSTimerExtensions.swift; sourceTree = "<group>"; };
E197F7BE1C7FD8C500FC6144 /* NSAttributedStringExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSAttributedStringExtensions.swift; sourceTree = "<group>"; };
E1CB3C1B1C25FFA000DF77CD /* DoubleExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DoubleExtensions.swift; path = Sources/DoubleExtensions.swift; sourceTree = SOURCE_ROOT; };
/* End PBXFileReference section */
@ -113,8 +117,10 @@
E1CB3C1B1C25FFA000DF77CD /* DoubleExtensions.swift */,
E1839E0E1BF79974002212C6 /* EZSwiftExtensions.swift */,
E1839E0F1BF79974002212C6 /* IntExtentions.swift */,
E197F7BE1C7FD8C500FC6144 /* NSAttributedStringExtensions.swift */,
E1839E101BF79974002212C6 /* NSDateExtensions.swift */,
E1839E111BF79974002212C6 /* NSObjectExtentions.swift */,
E197F7BC1C7FCE9D00FC6144 /* NSTimerExtensions.swift */,
E1839E121BF79974002212C6 /* StringExtensions.swift */,
E1839E131BF79974002212C6 /* UIButtonExtensions.swift */,
E1839E141BF79974002212C6 /* UIColoredView.swift */,
@ -245,6 +251,7 @@
E1839E301BF79974002212C6 /* UIColoredView.swift in Sources */,
E1839E1E1BF79974002212C6 /* ArrayExtensions.swift in Sources */,
E1839E2D1BF79974002212C6 /* NSObjectExtentions.swift in Sources */,
E197F7BD1C7FCE9D00FC6144 /* NSTimerExtensions.swift in Sources */,
E1839DB91BF79335002212C6 /* AppDelegate.swift in Sources */,
E1839E201BF79974002212C6 /* BlockLongPress.swift in Sources */,
E1839E381BF79974002212C6 /* UIViewControllerExtensions.swift in Sources */,
@ -261,6 +268,7 @@
E1839E241BF79974002212C6 /* BlockTap.swift in Sources */,
E1839E1F1BF79974002212C6 /* BlockButton.swift in Sources */,
E1839E311BF79974002212C6 /* UIColorExtensions.swift in Sources */,
E197F7BF1C7FD8C500FC6144 /* NSAttributedStringExtensions.swift in Sources */,
E1839E251BF79974002212C6 /* BlockWebView.swift in Sources */,
E1839E231BF79974002212C6 /* BlockSwipe.swift in Sources */,
E1839E221BF79974002212C6 /* BlockPinch.swift in Sources */,

View File

@ -14,7 +14,13 @@ class ViewController: UIViewController {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {

125
README.md
View File

@ -1,11 +1,34 @@
# EZSwiftExtensions
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/EZSwiftExtensions.svg)](https://img.shields.io/cocoapods/v/EZSwiftExtensions.svg)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/EZSwiftExtensions.svg)](https://img.shields.io/cocoapods/v/EZSwiftExtensions.svg)
<img src="charizard.png" width="200">
How Swift standard types and classes were supposed to work. A collection of useful extensions for the Swift Standard Library, Foundation, and UIKit.
### Contents
- [EZ functions and variables](#ez-functions-and-variables)
- [NSObject](#nsobject-extensions)
- [Bool](#bool-extensions)
- [Int](#int-extensions)
- [Double](#double-extensions)
- [String](#string-extensions)
- [Array](#array-extensions)
- [Dictionary](#dictionary-extensions)
- [NSDate](#nsdate-extensions)
- [CGRect](#cgrect-extensions)
- [UIViewController](#uiviewcontroller-extensions)
- [UIView](#uiview-extensions)
- [UITextView](#uitextview-extensions)
- [UILabel](#uilabel-extensions)
- [UIImageView](#uiimageview-extensions)
- [UIImage](#uiimage-extensions)
- [Block Objects](#block-objects)
- [UIDevice](#uidevice-extensions)
- [NSUserDefaults](#nsuserdefaults-extensions)
- [NSURL](#nsurl-extensions)
##EZ functions and variables:
Easily access your projects version and build numbers:
@ -82,22 +105,6 @@ ez.requestJSON("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=face
}
```
Easily run block of codes after a certain delay:
``` swift
ez.runThisAfterDelay(seconds: 2) { () -> () in
print("Prints this 2 seconds later in main queue")
}
```
Easily run code after delay in another thread:
``` swift
ez.runThisAfterDelay(seconds: 2, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { () -> () in
print("Prints this 2 seconds later in low priority queue")
}
```
Easily run code in main thread:
``` swift
@ -113,19 +120,6 @@ ez.runThisInBackground { () -> () in
}
```
Easily run code every seconds:
``` swift
var count = 0
ez.runThisEvery(seconds: 1) { (timer) -> Void in
print("Will print every second")
if count == 3 {
timer.invalidate()
}
count++
}
```
##NSObject Extensions
Easily get the name of your class:
@ -200,6 +194,7 @@ var myString = "eZSwiftExtensions"
print(myString[2]) // S
print(myString[3]) // w
print(myString[2...4]) // Swi
print(myString.getIndexOf("w") // 3
```
Easy instance variables:
@ -253,6 +248,32 @@ myNumberString.toInt()
myNumberString.toDouble()
myNumberString.toFloat()
```
Easily get the bool value of a String:
``` swift
let myString = "false"
let myOtherString = "hello"
print(myString.toBool()) // false
print(myOtherString.toBool()) // nil
```
Easily check if string is a number:
``` swift
let myStr = "10.5"
let myOtherStr = "Legolas"
print(myStr.isNumber()) // true
print(myOtherStr.isNumber()) // false
```
Easily count the number of instances of a text inside String:
``` swift
let str = "yes yes yes yesyesyes"
print(str.count("yes")) // 6
```
##Array Extensions
Easily access a random element:
@ -278,7 +299,7 @@ Easily check if an array contains instance of an object:
``` swift
var myArray = ["charmander","bulbasaur","squirtle"]
print(myArray.containsInstanceOf("hey")) // true
print(myArray.containsInstanceOf("charmander")) // true
print(myArray.containsInstanceOf(1)) // false
```
@ -326,6 +347,8 @@ Easily convert date into string:
``` swift
let now = NSDate()
print(now.toString())
print(now.toString(dateStyle: .MediumStyle, timeStyle: .MediumStyle))
print(now.toString(format: "yyyy/MM/dd HH:mm:ss"))
```
Easily see how much time passed:
@ -363,6 +386,35 @@ let now2 = NSDate()
print(now < now2) // true
print(now2 < now) // false
```
##NSTimer Extensions
Easily run block of codes after a certain delay:
``` swift
NSTimer.runThisAfterDelay(seconds: 2) { () -> () in
print("Prints this 2 seconds later in main queue")
}
```
Easily run code after delay in another thread:
``` swift
NSTimer.runThisAfterDelay(seconds: 2, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { () -> () in
print("Prints this 2 seconds later in low priority queue")
}
```
Easily run code every seconds:
``` swift
var count = 0
NSTimer.runThisEvery(seconds: 1) { (timer) -> Void in
print("Will print every second")
if count == 3 {
timer.invalidate()
}
count++
}
```
##CGRect Extensions
@ -641,6 +693,15 @@ Easily add a shake animation to your view:
view.shakeViewForTimes(2)
```
Easily add a background image to your ViewController:
``` swift
self.setBackgroundImage("img.png")
//OR
let image = UIImage()
self.setBackgroundImage(image)
```
##UITextView Extensions
Easily declare a UITextView with standard details:
@ -940,7 +1001,7 @@ if let queryParameters = url?.queryParameters {
## Install via CocoaPods (~10 seconds)
You can use [Cocoapods](http://cocoapods.org/) to install `EZSwiftExtensions` by adding it to your `Podfile`:
You can use [CocoaPods](http://cocoapods.org/) to install `EZSwiftExtensions` by adding it to your `Podfile`:
```ruby
platform :ios, '8.0'

View File

@ -9,7 +9,7 @@
import UIKit
extension CGFloat {
/// EZSwiftExtensions
/// EZSE: Return the central value of CGFloat.
public var center: CGFloat { return (self / 2) }
/// EZSwiftExtensions
@ -26,8 +26,9 @@ extension CGFloat {
public mutating func toRadiansInPlace() {
self = (CGFloat (M_PI) * self) / 180.0
}
}
/// EZSE: Converts angle degrees to radians.
public func degreesToRadians (angle: CGFloat) -> CGFloat {
return (CGFloat (M_PI) * angle) / 180.0
}
}

View File

@ -10,7 +10,7 @@ import UIKit
extension CGRect {
/// EZSwiftExtensions
/// EZSE: Easier initialization of CGRect
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
self.init(x: x, y: y, width: w, height: h)
}

View File

@ -8,13 +8,13 @@
import UIKit
extension Dictionary {
/// EZSwiftExtensions
/// EZSE: Returns a random element inside Dictionary
public func random() -> NSObject {
let index: Int = Int(arc4random_uniform(UInt32(self.count)))
return Array(self.values)[index] as! NSObject
}
/// EZSwiftExtensions, combines the first dictionary with the second and returns single dictionary
/// EZSE: Combines the first dictionary with the second and returns single dictionary
public func union(other: Dictionary) -> Dictionary {
var temp = self
for (key,value) in other {
@ -24,7 +24,7 @@ extension Dictionary {
}
}
/// EZSwiftExtensions
/// EZSE: Combines the first dictionary with the second and returns single dictionary
public func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)

View File

@ -9,9 +9,21 @@
import UIKit
extension Double {
/// EZSwiftExtensions
/// EZSE: Converts Double to String
public var toString: String { return String(self) }
/// EZSwiftExtensions
/// EZSE: Converts Double to Int
public var toInt: Int { return Int(self) }
/// EZSE: Returns a Double rounded to decimal
func getRoundedByPlaces(places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(self * divisor) / divisor
}
/// EZSE: Rounds the current Double rounded to decimal
mutating func roundByPlaces(places: Int) {
let divisor = pow(10.0, Double(places))
self = round(self * divisor) / divisor
}
}

View File

@ -11,29 +11,29 @@ import UIKit
public struct ez {
/// EZSwift Extensions
/// EZSE: Returns app's name
public static var appDisplayName: String {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleDisplayName") as? String
?? NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String
}
/// EZSwift Extensions
/// EZSE: Returns app's version number
public static var appVersion: String {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
/// EZSwiftExtensions
/// EZSE: Return app's build number
public static var appBuild: String {
return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as! String
}
/// EZSwiftExtensions
/// EZSE: Returns both app's version and build numbers "v0.3(7)"
public static var appVersionAndBuild: String {
let version = appVersion, build = appBuild
return version == build ? "v\(version)" : "v\(version)(\(build))"
}
/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
/// EZSE: Returns the top ViewController
public static var topMostVC: UIViewController? {
var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while let pVC = presentedVC?.presentedViewController {
@ -46,7 +46,7 @@ public struct ez {
return presentedVC
}
/// EZSwiftExtensions
/// EZSE: Returns current screen orientation
public static var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
@ -61,7 +61,7 @@ public struct ez {
return self.topMostVC?.traitCollection.verticalSizeClass ?? UIUserInterfaceSizeClass(rawValue: 0)!
}
/// EZSwiftExtensions
/// EZSE: Returns screen width
public static var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
@ -70,7 +70,7 @@ public struct ez {
}
}
/// EZSwiftExtensions
/// EZSE: Returns screen height
public static var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
@ -79,12 +79,12 @@ public struct ez {
}
}
/// EZSwiftExtensions
/// EZSE: Returns StatusBar height
public static var screenStatusBarHeight: CGFloat {
return UIApplication.sharedApplication().statusBarFrame.height
}
/// EZSwiftExtensions
/// EZSE: Return screen's height without StatusBar
public static var screenHeightWithoutStatusBar: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height - screenStatusBarHeight
@ -93,7 +93,7 @@ public struct ez {
}
}
/// EZSwiftExtensions - Calls action when a screen shot is taken
/// EZSE: Calls action when a screen shot is taken
public static func detectScreenShot(action: () -> ()) {
let mainQueue = NSOperationQueue.mainQueue()
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationUserDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in
@ -105,31 +105,31 @@ public struct ez {
// MARK: - Dispatch
/// EZSwiftExtensions
/// EZSE: Runs function after x seconds
public static func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
runThisAfterDelay(seconds: seconds, queue: dispatch_get_main_queue(), after: after)
}
//TODO: Make this easier
/// EZSwiftExtensions - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
/// EZSE: Runs function after x seconds with dispatch_queue, use this syntax: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
public static func runThisAfterDelay(seconds seconds: Double, queue: dispatch_queue_t, after: ()->()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, queue, after)
}
/// EZSwiftExtensions - Submits a block for asynchronous execution on the main queue
/// EZSE: Submits a block for asynchronous execution on the main queue
public static func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
/// EZSwiftExtensions - Runs in Default priority queue
/// EZSE: Runs in Default priority queue
public static func runThisInBackground(block: () -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
}
/// EZSwiftExtensions - Runs every second, to cancel use: timer.invalidate()
/// EZSE: Runs every second, to cancel use: timer.invalidate()
public static func runThisEvery(seconds seconds: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = CFAbsoluteTimeGetCurrent()
let fireDate = CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
@ -137,7 +137,7 @@ public struct ez {
// MARK: - DownloadTask
/// EZSwiftExtensions
/// EZSE: Downloads image from url string
public static func requestImage(url: String, success: (UIImage?) -> Void) {
requestURL(url, success: { (data) -> Void in
if let d = data {
@ -146,7 +146,7 @@ public struct ez {
})
}
/// EZSwiftExtensions
/// EZSE: Downloads JSON from url string
public static func requestJSON(url: String, success: (AnyObject? -> Void), error: ((NSError) -> Void)?) {
requestURL(url,
success: { (data)->Void in
@ -160,7 +160,7 @@ public struct ez {
})
}
/// EZSwiftExtensions
/// EZSE: converts NSData to JSON dictionary
private static func dataToJsonDict(data: NSData?) -> AnyObject? {
if let d = data {
var error: NSError?
@ -184,7 +184,7 @@ public struct ez {
}
}
/// EZSwiftExtensions
/// EZSE:
private static func requestURL(url: String, success: (NSData?) -> Void, error: ((NSError) -> Void)? = nil) {
guard #available(iOS 9, *) else {
NSURLConnection.sendAsynchronousRequest(

View File

@ -9,7 +9,7 @@ import UIKit
extension NSDate {
/// EZSwiftExtensions
/// EZSE: Initializes NSDate from string and format
public convenience init?(fromString string: String, format: String) {
let formatter = NSDateFormatter()
formatter.dateFormat = format
@ -20,50 +20,50 @@ extension NSDate {
}
}
/// EZSwiftExtensions
public func toString() -> String {
/// EZSE: Converts NSDate to String
public func toString(dateStyle dateStyle: NSDateFormatterStyle = .MediumStyle, timeStyle: NSDateFormatterStyle = .MediumStyle) -> String {
let formatter = NSDateFormatter()
formatter.timeStyle = NSDateFormatterStyle.NoStyle
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
return formatter.stringFromDate(self)
}
/// EZSwiftExtensions
public func toStringUsingFormat(format: String) -> String {
/// EZSE: Converts NSDate to String, with format
public func toString(format format: String) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(self)
}
/// EZSwiftExtensions
}
/// EZSE: Calculates how many days passed from now to date
public func daysInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/86400)
return diff
}
/// EZSwiftExtensions
/// EZSE: Calculates how many hours passed from now to date
public func hoursInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/3600)
return diff
}
/// EZSwiftExtensions
/// EZSE: Calculates how many minutes passed from now to date
public func minutesInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/60)
return diff
}
/// EZSwiftExtensions
/// EZSE: Calculates how many seconds passed from now to date
public func secondsInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff)
return diff
}
/// EZSwiftExtensions
/// EZSE: Easy creation of time passed String. Can be Years, Months, days, hours, minutes or seconds
public func timePassed() -> String {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
@ -95,11 +95,11 @@ extension NSDate {
}
extension NSDate: Comparable {}
/// EZSE: Returns if dates are equal to each other
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
/// EZSE: Returns if one date is smaller than the other
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}

View File

@ -9,13 +9,13 @@ import UIKit
extension String {
/// EZSwiftExtensions
/// EZSE: Cut string from integerIndex to the end
public subscript(integerIndex: Int) -> Character {
let index = startIndex.advancedBy(integerIndex)
return self[index]
}
/// EZSwiftExtensions
/// EZSE: Cut string from range
public subscript(integerRange: Range<Int>) -> String {
let start = startIndex.advancedBy(integerRange.startIndex)
let end = startIndex.advancedBy(integerRange.endIndex)
@ -23,43 +23,56 @@ extension String {
return self[range]
}
/// EZSwiftExtensions - Character count
/// EZSE: Character count
public var length: Int {
return self.characters.count
}
/// EZSE: Counts number of instances of the input inside String
func count(substring: String) -> Int{
return componentsSeparatedByString(substring).count - 1
}
/// EZSwiftExtensions
/// EZSE: Capitalizes first character of String
public var capitalizeFirst: String {
var result = self
result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
return result
}
/// EZSwiftExtensions - Counts whitespace & new lines
/// EZSE: Counts whitespace & new lines
public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let newText = self.stringByTrimmingCharactersInSet(characterSet)
return newText.isEmpty
}
/// EZSwiftExtensions - Trims white space and new line characters
/// EZSE: Trims white space and new line characters
public mutating func trimInPlace() {
self = self.trim()
}
/// EZSwiftExtensions
/// EZSE: Trims white space and new line characters, returns a new string
public func trim() -> String {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("")
}
/// EZSwiftExtensions
}
/// EZSE: Checks if String contains Email
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let firstMatch = dataDetector?.firstMatchInString(self, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.URL?.scheme == "mailto")
}
/// EZSwiftExtensions
/// EZSE: Returns if String is a number
func isNumber() -> Bool {
if let _ = NSNumberFormatter().numberFromString(self) {
return true
}
return false
}
/// EZSE: Extracts URLS from String
public var extractURLs: [NSURL] {
var urls : [NSURL] = []
let detector: NSDataDetector?
@ -79,17 +92,17 @@ extension String {
return urls
}
/// EZSwiftExtensions
/// EZSE: Checking if String contains input
public func contains(find: String) -> Bool {
return self.rangeOfString(find) != nil
}
/// EZSwiftExtensions
/// EZSE: Checking if String contains input with comparing options
public func contains(find: String, compareOption: NSStringCompareOptions) -> Bool {
return self.rangeOfString(find, options: compareOption) != nil
}
/// EZSwiftExtensions
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.integerValue
@ -98,7 +111,7 @@ extension String {
}
}
/// EZSwiftExtensions
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.doubleValue
@ -107,7 +120,7 @@ extension String {
}
}
/// EZSwiftExtensions
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.floatValue
@ -116,8 +129,51 @@ extension String {
}
}
/// EZSwiftExtensions
/// EZSE: Converts String to Bool
func toBool() -> Bool? {
let trimmed = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).lowercaseString
if trimmed == "true" || trimmed == "false" {
return (trimmed as NSString).boolValue
}
return nil
}
///EZSE: Returns the first index of the occurency of the character in String
public func getIndexOf(char: Character) -> Int? {
for (index, c) in characters.enumerate() {
if c == char {
return index
}
}
return nil
}
/// EZSE: Converts String to NSString
public var toNSString: NSString { get { return self as NSString } }
///EZSE: Returns bold NSAttributedString
func bold() -> NSAttributedString {
let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())])
return boldString
}
///EZSE: Returns underlined NSAttributedString
func underline() -> NSAttributedString {
let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
return underlineString
}
///EZSE: Returns italic NSAttributedString
func italic() -> NSAttributedString {
let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())])
return italicString
}
///EZSE: Returns NSAttributedString
func color(color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
return colorString
}
}

View File

@ -9,13 +9,8 @@ import UIKit
extension UIColor {
/// EZSwiftExtensions
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1)
}
/// EZSwiftExtensions
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
/// EZSE: init method with RGB values from 0 to 255, instead of 0 to 1
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
@ -38,14 +33,9 @@ extension UIColor {
}
}
/// EZSwiftExtensions
public class func Gray(gray: CGFloat) -> UIColor {
return UIColor(r: gray, g: gray, b: gray)
}
/// EZSwiftExtensions
public class func Gray(gray: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(r: gray, g: gray, b: gray, a: alpha)
/// EZSE: init method from Gray value
public convenience init(gray: CGFloat, alpha: CGFloat = 1) {
self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha)
}
/// EZSwiftExtensions

View File

@ -56,11 +56,26 @@ extension UIFont {
}
/// EZSwiftExtensions
public class func Font(name: FontName, type: FontType, size: CGFloat) -> UIFont {
if type == FontType.None {
return UIFont(name: name.rawValue, size: size)!
}
return UIFont(name: name.rawValue + "-" + type.rawValue, size: size)!
public class func Font(name: FontName, type: FontType, size: CGFloat) -> UIFont! {
//Using type
let fontName = name.rawValue + "-" + type.rawValue
if let font = UIFont(name: fontName, size: size) {
return font
}
//That font doens't have that type, try .None
let fontNameNone = name.rawValue
if let font = UIFont(name: fontNameNone, size: size) {
return font
}
//That font doens't have that type, try .Regular
let fontNameRegular = name.rawValue + "-" + "Regular"
if let font = UIFont(name: fontNameRegular, size: size) {
return font
}
return nil
}
/// EZSwiftExtensions
@ -70,17 +85,17 @@ extension UIFont {
/// EZSwiftExtensions
public class func AvenirNext(type type: FontType, size: CGFloat) -> UIFont {
return UIFont.Font(.AvenirNext, type: type, size: size)
return Font(.AvenirNext, type: type, size: size)
}
/// EZSwiftExtensions
public class func AvenirNextDemiBold(size size: CGFloat) -> UIFont {
return AvenirNext(type: .DemiBold, size: size)
return Font(.AvenirNext, type: .DemiBold, size: size)
}
/// EZSwiftExtensions
public class func AvenirNextRegular(size size: CGFloat) -> UIFont {
return AvenirNext(type: .Regular, size: size)
return Font(.AvenirNext, type: .Regular, size: size)
}
}

View File

@ -9,25 +9,25 @@ import UIKit
extension UIImage {
/// EZSwiftExtensions - rate: 0 to 1
/// EZSE: Returns compressed image to rate from 0 to 1
public func compressImage(rate rate: CGFloat) -> NSData {
let compressedImage = UIImageJPEGRepresentation(self, rate)
return compressedImage!
}
/// EZSwiftExtensions
/// EZSE: Returns Image size in Bytes
public func getSizeAsBytes() -> Int {
let imageData = NSData(data: UIImageJPEGRepresentation(self, 1)!)
return imageData.length
}
/// EZSwiftExtensions
/// EZSE: Returns Image size in Kylobites
public func getSizeAsKilobytes() -> Int {
let imageData = NSData(data: UIImageJPEGRepresentation(self, 1)!)
return imageData.length / 1024
}
/// EZSwiftExtensions
/// EZSE: scales image
public class func scaleTo(image image: UIImage, w: CGFloat, h: CGFloat) -> UIImage {
let newSize = CGSize(width: w, height: h)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
@ -37,7 +37,7 @@ extension UIImage {
return newImage
}
/// EZSwiftExtensions, might return low quality
/// EZSE Returns resized image with width. Might return low quality
public func resizeWithWidth(width: CGFloat) -> UIImage {
let aspectSize = CGSize (width: width, height: aspectHeightForWidth(width))
@ -49,7 +49,7 @@ extension UIImage {
return img
}
/// EZSwiftExtensions, might return low quality
/// EZSE Returns resized image with height. Might return low quality
public func resizeWithHeight(height: CGFloat) -> UIImage {
let aspectSize = CGSize (width: aspectWidthForHeight(height), height: height)
@ -61,22 +61,36 @@ extension UIImage {
return img
}
/// EZSwiftExtensions
/// EZSE:
public func aspectHeightForWidth(width: CGFloat) -> CGFloat {
return (width * self.size.height) / self.size.width
}
/// EZSwiftExtensions
/// EZSE:
public func aspectWidthForHeight(height: CGFloat) -> CGFloat {
return (height * self.size.width) / self.size.height
}
/// EZSwiftExtensions
/// EZSE: Returns cropped image from CGRect
public func croppedImage(bound: CGRect) -> UIImage {
let scaledBounds: CGRect = CGRectMake(bound.origin.x * self.scale, bound.origin.y * self.scale, bound.size.width * self.scale, bound.size.height * self.scale)
let imageRef = CGImageCreateWithImageInRect(self.CGImage, scaledBounds)
let croppedImage: UIImage = UIImage(CGImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.Up)
return croppedImage
}
///EZSE: Returns the image associated with the URL
public convenience init?(urlString: String) {
guard let url = NSURL(string: urlString) else {
self.init(data: NSData())
return
}
guard let data = NSData(contentsOfURL: url) else {
print("EZSE: No image in URL")
self.init(data: NSData())
return
}
self.init(data: data)
}
}

View File

@ -221,5 +221,23 @@ extension UIViewController {
self.addChildViewController(vc)
vc.didMoveToParentViewController(self)
}
///EZSE: Adds image named: as a UIImageView in the Background
func setBackgroundImage(named: String) {
let image = UIImage(named: named)
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
///EZSE: Adds UIImage as a UIImageView in the Background
@nonobjc func setBackgroundImage(image: UIImage) {
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
}

View File

@ -274,6 +274,7 @@ extension UIView {
transform = CATransform3DScale(transform, x, y, 1)
self.layer.transform = transform
}
}
// MARK: Layer Extensions
@ -508,9 +509,10 @@ extension UIView {
}
/// EZSwiftExtensions
public func round() {
self.layer.cornerRadius = self.frame.size.width / 2
public func roundView() {
self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) / 2
}
}
extension UIView {