💪 Ultimate package of useful Swift Utilities.
Forget about creating a new Utils
folder and adding the same extensions again when you create a new project.🗑
Simply add Swing
to get going with the essential Swift Utility functions.
Currently, only iOS is fully supported. Support for other platforms will be coming soon.
In your Xcode Project, go to File -> Swift Packages -> Add Package Dependency -> https://github.com/mininny/Swing
If you do not prefer having all of the files added to your projects, simply copy & paste the code snippets that you like!
There is no restriction upon what you can do with this library, and it is licensed under WTFPL. :)
makes the corner of the view rounded.
guard let side = [self.frame.width, self.frame.height].min() else { return }
self.layer.cornerRadius = side/2
returns the topmost view controller of the current window
if var topController = UIWindow.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
returns the keyWindow of the application
UIApplication.shared.windows.filter {$0.isKeyWindow}.first
returns the UIColor of given CGPoint in a UIView.
guard let pixelData = self.cgImage?.dataProvider?.data else { return nil }
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
initializes UIColor with given hex string value and alpha value.
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return nil
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha
)
returns a UIColor with given hex string value and alpha value.
UIColor(fromHex: hex, alpha: alpha)
converts UIColor to hexString
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return NSString(format:"#%06x", rgb) as String
returns localized string with the given comment
NSLocalizedString(self, comment: comment)
remove all characters in the string except
count
number of characters. Trailing characters are trimmed by default.
if self.count > count {
self.removeLast(self.count - count)
} else {
self = ""
}
whitespace and newline trimmed string. Returns nil if trimmed string is empty, and regular string otherwise.
let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
removes all components of the given
Date
until the specifiedcomponent
i.e., for removeTimestamp(keeping: .day), returned Date will look like
June, 7, 2020
var calendarComponents: [Calendar.Component] = [ .nanosecond,
.second,
.minute,
.hour,
.day,
.month,
.era,
.year,
.timeZone,
.calendar]
switch component {
case .nanosecond: break
case .second:
calendarComponents.removeFirst(1)
case .minute:
calendarComponents.removeFirst(2)
case .hour:
calendarComponents.removeFirst(3)
case .day:
calendarComponents.removeFirst(4)
case .month:
calendarComponents.removeFirst(5)
case .year:
calendarComponents.removeFirst(6)
case .era:
calendarComponents.removeFirst(7)
case .timeZone:
calendarComponents.removeFirst(8)
case .calendar:
calendarComponents.removeFirst(9)
}
return Calendar.current.date(from: Calendar.current.dateComponents(Set(calendarComponents), from: self))
returns the hex value representation of the given
Data
. Useful when dealing with push tokens.
var hexString: String { self.map { String(format: "%02x", $0) }.joined() }
returns nil if the subscript does not exist in the collection's indexes. Returns regular value if it exists. Useful when dealing with safe collection handling
return indices.contains(index) ? self[index] : nil
returns the
CFBundleShortVersionString
of the bundle, aka. version number, of the project.
self.infoDictionary?["CFBundleShortVersionString"] as? String
returns the
CFBundleName
of the bundle, aka. bundle name, of the project.
self.infoDictionary?["CFBundleName"] as? String
returns the
CFBundleVersion
of the bundle, aka. build number, of the project.
self.infoDictionary?["CFBundleVersion"] as? String
create a
UIAlertController
and present it on the viewController.
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
if options.showOK{
let okAction = UIAlertAction(title: options.defaultTitle, style: .default, handler: nil)
alert.addAction(okAction)
}
if options.showCancel {
let cancelAction = UIAlertAction(title: options.cancelTitle, style: .cancel, handler: nil)
alert.addAction(cancelAction)
}
vc.present(alert, animated: options.animate, completion: completion)
Helper module that observes changes in iOS Keyboard. You can register custom handler that gets called when the keyboard's frame changes.
Registers a
KeyboardHeightHandler
handler that observes change in keyboard frame.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
self.keyBoardNotificationHandler = handler
Removes the registered
KeyboardHeightHandler
and stops observing keyboard changes.
NotificationCenter.default.removeObserver(self)
self.keyBoardNotificationHandler = nil
Add custom observers to the keyboard using given selectors.
if let action = showAction {
NotificationCenter.default.addObserver(observer, selector: action, name: UIWindow.keyboardWillShowNotification, object: nil)
}
if let action = hideAction {
NotificationCenter.default.addObserver(observer, selector: action, name: UIWindow.keyboardWillHideNotification, object: nil)
}
Helper module that uses objective-C API to do things that are impossible with Swift.
Saves a value to the container with a specific key using
objc_setAssociatedObject
.This allows you to create stored properties within a extension, for example.
objc_setAssociatedObject(self, key, value, policy)
Retrieves the value from the container with a specific key using
objc_getAssociatedObject
.
return objc_getAssociatedObject(self, key) as? T
Helper module that contains extensions that makes unit test implementation and mocking easier.
return UUID().uuidString
Feel free to create requests for new methods!
link |
Stars: 1 |
Last commit: 3 years ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics