Skip to content

Instantly share code, notes, and snippets.

@andytlr
Last active July 16, 2018 07:35
Show Gist options
  • Save andytlr/9bb208cb7d36b8914180 to your computer and use it in GitHub Desktop.
Save andytlr/9bb208cb7d36b8914180 to your computer and use it in GitHub Desktop.
Swift Snippets

Swift Snippets

Change Status Bar

To make it light, put this inside the View Controller class:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return .LightContent
}

Or to hide it completely:

override func prefersStatusBarHidden() -> Bool {
  return true
}

Make a scroll view with a big image scroll

Tell the scrollView to be the same size as the imageView:

scrollView.contentSize = imageView.frame.size

Or, set it to a pixel size:

scrollView.contentSize = CGSize(width:375, height:1857)

Control a child view controller from a parent.

Define the first [0] of the child view controllers with the class name ChildViewControllerClassName as a variable childVC:

let childVC = self.childViewControllers[0] as! ChildViewControllerClassName

Put childVC. before the var you want to control from the child VC:

childVC.thingToControl.alpha = 1

Go Back in Code

Dismiss a modal:

dismissViewControllerAnimated(true, completion: nil)

Go back in the history stack:

navigationController!.popViewControllerAnimated(true)

Do stuff when going back to a view

viewDidLoad() only runs the first time a view loads. If you want to do something when you pop a view try viewDidAppear() or viewWillAppear().

override func viewDidAppear(animated: Bool) {
}

Set scroll position

let scrollTo = CGPointMake(0.0, 57.0)
scrollView.setContentOffset(scrollTo, animated: true)

Perform a Segue

Name your segue by clicking on the line that connects the views in your story board. Go to the Attribues Inspector and give your segue an Indetifier, e.g. SegueName.

performSegueWithIdentifier("SegueName", sender: self)

Pass a variable on Segue

In the view controller that you want to receive the variable, set an empty variable and give it a type.

var emptyVariableInDestinationViewController: Bool!

In Source View Controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
  // Set the destination view controller name at the end of this line.
  let destinationVC = segue.destinationViewController as! DestinationViewControllerClassName
  // Give it a value at the end of this line.
  destinationVC.emptyVariableInDestinationViewController = thingIWantToSetItTo
}

Autolayout getting f-d up?

In viewDidLoad():

self.automaticallyAdjustsScrollViewInsets = false

Get scroll position

See this commit.

Gesture recognizer stuff

Most common properties in a gesture. These are CGPoints, add .x or .y for axis:

let location = sender.locationInView(view)
let translation = sender.translationInView(view)
let velocity = sender.velocityInView(view)

These states go inside the gesture recognizer method:

if sender.state == .Began {
  // Runs once on start of gesture
}
if sender.state == .Changed {
  // Runs constantly as the gesture changes
}
if sender.state == .Ended {
  // Runs once when the gesture ends
}

Send and Listen for Notifications

Where you want to send the notification:

NSNotificationCenter.defaultCenter().postNotificationName("Finished Saving To Camera Roll", object: nil)

If you're sending from a non-view file, you might need to wrap it in this to make sure it's on the main thread:

dispatch_async(dispatch_get_main_queue()) {
  //
}

Then add an 'observer'/listener in the view you want to know about the notification (probably in viewDidLoad):

NSNotificationCenter.defaultCenter().addObserver(self, selector: "runWhenFinishedSavingToCameraRoll", name: "Finished Saving To Camera Roll", object: nil)

Then run the function with that selector at the class level:

unc runWhenFinishedSavingToCameraRoll() {
  // Tell user it finished saving
}

Make Xcode Editing More Like Atom/Sublime

Go to Settings > Keybindings to remap or add keyboard shortcuts. When removing existing keybindings, don't press the keyboard Delete key, click the icon. Some keybindings can't be deleted ¯\_(ツ)_/¯; remap these to keybindings that are available.

Multiple Selection

Xcode has something called "Edit All in Scope" (ctrl + cmd + e). It's similar but just selects all instances of the selected text.

Open Quickly

command + shift + o

Delete Line & Duplicate Line

There aren't actually commands for Delete Line and Duplicate Line, but you can edit a plist file to chain multiple actions together into one command. After editing the .plist you can add a shortcuts in Settings > Keybindings.

Open /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Resources/IDETextKeyBindingSet.plist and put this before the closing </dict> and </plist> tags:

<key>Custom</key>
<dict>
  <key>Delete Line</key>
  <string>moveToEndOfLine:, deleteToBeginningOfLine:, deleteToEndOfParagraph:</string>
  <key>Duplicate Line</key>
  <string>moveToBeginningOfLine:, deleteToEndOfLine:, yank:, insertNewline:, moveToBeginningOfLine:, yank:</string>
</dict>

Move Line

There are commands for Move Line Up and Move Line Down (cmd + option + [/]).

More shortcuts

This NSHipster Article covers a lot of other shortcuts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment