Skip to content

Instantly share code, notes, and snippets.

@algal
algal / ImageToURL.swift
Created July 10, 2015 23:50
Save a UIImage into a URL
/// Save image in an in-memory URL
func toURL(image:UIImage) -> NSURL
{
let img = image
let imgData:NSData = UIImagePNGRepresentation(img)
let dataFormatString = "data:image/png;base64,%@"
let dataString = String(format: dataFormatString, imgData.base64EncodedStringWithOptions(.allZeros))
let dataURL = NSURL(string: dataString)!
return dataURL
}
@algal
algal / VerticallyStackViewHelpers.swift
Created July 14, 2015 23:04
Vertically stacking views
/**
Adds views to containerView, along with constraints to stack them vertically
and fill horozintally.
*/
func addVerticallyStackedViews(views:[UIView], toView containerView:UIView) -> [NSLayoutConstraint]
{
for v in views {
v.setTranslatesAutoresizingMaskIntoConstraints(false)
containerView.addSubview(v)
}
@algal
algal / NonGenericWrapperCollectionViewCell.swift
Last active March 8, 2017 17:15
Non-generic WrapperCollectionViewCell
import UIKit
// known-good: Swift 3
/**
Abstract superclass for quickly defining a `UICollectionViewCell` subclass that wraps a
specific `UIView` subclass. The resulting `UICollectionViewCell` will hug the wrapped view
with layout constraints, so that both the cell and the wrapped view can influence
each other's size via the normal Auto Layout mechanism.
To use, override the class function `wrappedViewType` and the computed property
// code from: http://stackoverflow.com/questions/2451223/uibutton-how-to-center-an-image-and-a-text-using-imageedgeinsets-and-titleedgei/24294816#24294816
extension UIButton {
func centerLabelVerticallyWithPadding(spacing:CGFloat) {
// update positioning of image and title
let imageSize = self.imageView.frame.size
self.titleEdgeInsets = UIEdgeInsets(top:0,
left:-imageSize.width,
bottom:-(imageSize.height + spacing),
right:0)
@algal
algal / waitUntilTrue.swift
Last active August 30, 2015 05:19
Pause execution in a playground until a condition is met (like an async network load completing)
// in a playground, pause execution wait until the condition pred is true
func waitUntilTrue(@autoclosure pred:()->Bool, secondsUntilTimeout duration:NSTimeInterval = 25)
{
let previousPlayGroundRunStatus = XCPExecutionShouldContinueIndefinitely()
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
let start = NSDate()
while true {
if pred() {
NSLog("condition met.")
@algal
algal / NSURLSessionAllowBadCertificateDelegate.swift
Last active August 30, 2015 05:23
Configure an NSURLSession so that it will load HTTPS even from servers with invalid TLS certificate
// works as of Swift 1.2, 2015-08-29
// https://developer.apple.com/library/ios/technotes/tn2232/_index.html#//apple_ref/doc/uid/DTS40012884-CH1-SECNSURLSESSION
class NSURLSessionAllowBadCertificateDelegate : NSObject, NSURLSessionDelegate
{
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)
{
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
{
// Swift 1.2
// synchronous JSON download
import XCPlayground
// my goodness all this complexity is just for an unconditional synchronous
// get in a playground on HTTP or HTTPS and decoding to JSON. sad.
public func waitUntilTrue(@autoclosure pred:()->Bool, secondsUntilTimeout duration:NSTimeInterval = 25)
{
@algal
algal / LineParagraphSpacing.swift
Last active September 21, 2015 19:46
Playground gist illustrating relation between line and paragraph breaks, and between line spacing and paragraph spacing
import UIKit
//: # Paragraphs, lines, breaks, and spacing in attributed strings
/*:
The cocoa text system lets you separately adjust line spacing and paragraph spacing.
This playground investigates a few questions concerning these spacing configurations and text layout:
1. Do empty UILabels collapse to zero height?
@algal
algal / NSAttributedStringBug.swift
Created September 25, 2015 17:53
Playground gist showing a bug in how NSAttributedString misinterprets LINE SEPARATOR
//: Playground - noun: a place where people can play
import UIKit
/*:
This playground shows a bug in how `NSAttributedString.boundingRectWithSize(_:options:context:)` handles attributed strings containing the LINE SEPARATOR character when the .UsesDeviceMetrics option is not included.
When the `.UsesDeviceMetrics` option is set, the function is supposed to return the bounding rect where the height is what is required to bound the particular glyphs in the string.
@algal
algal / SwiftRecursiveDescription.swift
Last active October 14, 2015 19:06
How to use UIView.recursiveDescription in a Swift playground
let v = UIView()
// use `performSelector` to workaround that the method is private
// use `takeRetainedValue` to get an AnyObject
// use the forced cast because we know it's a string
let s = v.performSelector("recursiveDescription").takeRetainedValue() as! String
// convert the string to a fixed width font, so the quicklook is useful
NSAttributedString(string: s, attributes: [UIFontDescriptorFeatureSettingsAttribute:[UIFontFeatureTypeIdentifierKey:kMonospacedTextSelector]])