Skip to content

Instantly share code, notes, and snippets.

@dabrahams
dabrahams / FactoryInitialization.swift
Last active June 5, 2024 20:44
Class factory initializers
/// Classes whose initializers actually create derived classes
protocol FactoryInitializable {
/// The type of the least-derived class declared to be FactoryInitializable.
///
/// - Warning: Do not define this in your FactoryInitializable type!
associatedtype FactoryBase: AnyObject, FactoryInitializable = Self
// This associatedtype is a trick that captures `Self` at the point where
// `FactoryInitializable` enters a class hierarchy; in other contexts, `Self`
// refers to the most-derived type.
}
@romanmiller
romanmiller / UIButton + SpringAnimation
Last active March 18, 2017 10:04
Spring animation for UIButton (can use in extension for UIButton or for your custom button class) (Swift)
// from: size that button start animated; duration: time for animation;
func animateSpring(from: CGFloat,duration: TimeInterval) {
let scale = from / self.bounds.height
self.transform = CGAffineTransform(scaleX: scale, y: scale)
UIView.animate(withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.4,
@trilliwon
trilliwon / uiimage-data.swift
Last active January 12, 2024 14:45
Swift UIImage to Data, Data to UIImage
// Swift4
let image = UIImage(named: "sample")
let data = image?.pngData()
let data = image?.jpegData(compressionQuality: 0.9)
let uiImage: UIImage = UIImage(data: imageData)
// deprecated
// var imageData: Data = UIImagePNGRepresentation(image)
@AmitaiB
AmitaiB / SwiftXOR.swift
Created November 17, 2016 04:41
Swift 3 Logical XOR Operator
precedencegroup BooleanPrecedence { associativity: left }
infix operator ^^ : BooleanPrecedence
/**
Swift Logical XOR operator
```
true ^^ true // false
true ^^ false // true
false ^^ true // true
false ^^ false // false
```
@alonecuzzo
alonecuzzo / Header.swift
Created November 16, 2015 23:47
Get HeaderView Sized with SnapKit
//
// ViewController.swift
// SnapKitTest
//
// Created by Robert Payne on 10/11/15.
// Copyright © 2015 Zwopple Limited. All rights reserved.
//
import SnapKit
import UIKit
@benjaminhorner
benjaminhorner / ScrollTextFieldAboveKeyboard
Last active May 31, 2022 12:21
Scroll UITextField above Keyboard in a UITableView OR UIScrollView in Swift
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
let contentInsets = UIEdgeInsets(top: self.tableView.contentInset.top, left: 0, bottom: keyboardSize.height, right: 0)
self.tableView.contentInset = contentInsets
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardSize.height
let activeTextFieldRect: CGRect?