Skip to content

Instantly share code, notes, and snippets.

@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)
}
// 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 / :(.swift
Last active September 4, 2015 12:18 — forked from chriseidhof/:(
import Foundation
import ImageIO
//
// before
//
func datesFromImagesInDir(dir: String) -> [NSDate] {
let fm = NSFileManager.defaultManager()
@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]])
@algal
algal / PathOutliningPath.swift
Created October 23, 2015 06:00
Get the outline of a path
/// Given `path`, drawn with `width`, returns a new path outlining its edges
func pathOutliningPath(path:UIBezierPath, withWidth width:CGFloat, inSize size:CGSize) -> UIBezierPath
{
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let ctx = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(ctx, width)
CGContextAddPath(ctx, path.CGPath)
CGContextReplacePathWithStrokedPath(ctx)
let extractedCGPath = CGContextCopyPath(ctx)
UIGraphicsEndImageContext()