A colleague of mine has the practice of collapsing all the methods in an Objective C file when he loads it to simplify finding the right method to view. When I asked him how he did it, he couldn’t remember since it was an automatic action. I finally got around to figuring out how to do it.
The feature is called Code Folding and can be done using the pointer, the menu bar, and the keyboard.
Code Folding using the Pointer
You may have noticed the different colored gray bars on the left of your code in Xcode and may have even accidentally hovered over one of them and been treated to a drastic change in the UI. Those gray bars allow you to fold – or collapse – your code. Using those bars, you can fold any size block, such as an if block, a for block, an @synchronized block, or even a whole method block.
Hovering over the gray bar shows you the block that will be folded. Clicking on the gray bar folds the block and shows a yellow ellipsis between the curly braces where the block used to be. It also changes the gray bar to an arrow. Clicking the arrow or double-clicking the ellipsis will unfold – or expand – the folded block.
Code Folding using the Menu Bar
The code folding functionality is exposed in the menus accessible from the menu bar as well. In Xcode 4, check out Editor -> Code Folding.
Code Folding using the Keyboard
Apple has defined default keystrokes for code folding, but I found that some of them conflicted with keystrokes defined for other functions. In most cases the conflicts were caused by changes I had made – either in Xcode or in Mac OS X Lion – to accommodate writing code.
The following code folding functionality can be controlled using the keyboard:
- Fold all methods and functions – Option + Cmd + Shift + Left Arrow
- Unfold all methods and functions – Option + Cmd + Shift + Right Arrow
- Fold the current block – Option + Cmd + Left Arrow
- Unfold the current block – Option + Cmd + Right Arrow
I had to change the fold/unfold block key bindings because they conflicted with the key bindings I had selected for switching between Spaces in Lion. I changed them to Ctrl + Cmd + Shift + Left Arrow/Right Arrow respectively. This, of course, required that I change another key binding in Xcode – the key bindings for fold/unfold comment blocks.
Comment blocks are blocks of comments using /* and */ as delimiters. Since I almost never use this style of commenting, removing the key binding for folding/unfolding comment blocks in favor of code folding/unfolding was a good trade-off for me.
great! thanks!
Hi just wondering what your commenting style is if not the usual /* and */ ?
I prefer to use full-line comments, e.g.:
// This is a full line comment.