Skip to content

Instantly share code, notes, and snippets.

@chenr2
chenr2 / tabBarColor.swift
Created July 16, 2015 11:38
Swift: How to set the tab bar color
tabBarController?.tabBar.selectedImageTintColor = .redColor()
@chenr2
chenr2 / suppressCallout.swift
Last active August 29, 2015 14:25
Swift: How to suppress callout for user location
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
// user location
if annotation is MKUserLocation {
(annotation as! MKUserLocation).title = ""
// use blue pulsy instead of pin
return nil
}
// other pins
return mapView.dequeueReusableAnnotationViewWithIdentifier("pin") as? MKPinAnnotationView
}
@chenr2
chenr2 / dispatch.swift
Created July 16, 2015 11:46
Swift snippet: hop back to the main thread
dispatch_async(dispatch_get_main_queue()) {
self.someMethod(self.someProperty)
}
@chenr2
chenr2 / alertview.md
Last active August 29, 2015 14:25
Swift UIAlertView for iOS 7 compatibility. Also demonstrates adding a TextField to the AlertView.

Using UIAlertView

UIAlertView is deprecated, so use it for iOS 7 compatibility. Otherwise, use UIAlertController.

let alertView = UIAlertView()
alertView.message = "here"
alertView.addButtonWithTitle("Ok")
alertView.show()
@chenr2
chenr2 / collectionCellSizes.md
Last active February 18, 2019 11:08
Swift: Handle rotation for UICollectionView cell sizes

Handle rotation for UICollectionView cell sizes

Requires iOS 8+

Say you want 3 cells per row in portrait, but 4 cells in landscape. First calculate the cell dimensions based on the screen width and a padding of 5.

var cellsPerRow:CGFloat = 3
let cellPadding:CGFloat = 5
@chenr2
chenr2 / println.md
Last active August 29, 2015 14:25
Swift: Caveman debugging with println

Caveman debugging with println

Here's a handy snippet when inspecting the network response.

println("request:: \(request)")
println("response:: \(response)")
println("data:: \(data)") 
println("error:: \(error)")
@chenr2
chenr2 / nsnotification.md
Last active August 29, 2015 14:25
Swift: NSNotification basics

NSNotification basics

This is how you fire an event:

NSNotificationCenter.defaultCenter().postNotificationName("doSomething", object: nil)

Elsewhere, listen for the event like so:

Error when performing segue on viewDidLoad

Getting this error message:

Presenting view controllers on detached view controllers is discouraged

This is happening because you’re not supposed to perform a segue until viewDidAppear

@chenr2
chenr2 / stringify.md
Last active August 29, 2015 14:25
Swift: JSON stringify

How to stringify JSON

This assumes you have SwiftyJSON.

Start with a Dictionary

let paramsDictionary = [
    "title": "foo",
 "description": "bar"