Saturday 4 October 2014

Size Classes with Xcode 6: One storyboard for all Sizes Part - II

My favourite feature of Xcode 6 so far is the new size classes concept in Interface Builder. Size classes are Apple's solution to the question "How can I easily work with so many different screen sizes and device orientations?" They also enable the condensing of universal apps into one storyboard file. Combined with the new adaptive view controllers, it's easier then ever to rely on interface builder, rather than fight with it, to simplify the creation of your app layouts.
⇨Every view controller in your app gets a trait collection object.
This trait collection object has 2 size classes: a horizontal size class and a vertical size class.
And each of these classes has 3 possible values:
compact, regular, or any.
⇨These values can change based on the device and its orientation. Your app will layout its interface for each view controller based on the current size classes. Apple uses a grid to let the user choose which configuration to work in, so here's that same grid but with each device+orientation highlighted in its corresponding size class combo:
⇨One interesting thing to note here: iPad has regular x regular for both landscape and portrait. Straight from Apple's 'What's new in iOS8 guide'
“With the amount of screen space available, the iPad has a regular size class in the vertical and horizontal directions in both portrait and landscape orientations.”
Ok, enough by-the-books stuff, lets open up Xcode 6 and try it out for ourselves. 
⇨Create a new universal project for this demo. If you want to try it out in an existing Xcode 6 project, then you might have to explicitly enable size classes. You can do this in Interface Builder in the file inspector, right below the enable autolayout checkmark.
⇨First, let's look at the size class grid in Xcode. This is the area where you can switch your storyboard between the different layout combinations. While viewing your storyboard, look towards the bottom and Click on the label that says "wAny hAny".
You will see something that looks like the grid from the top of this post.
⇨By default, we start in our base configuration of any width and any height. Think of this as your master interface, things setup and changed here will be used by both the iPhone and iPad layout by default for all orientations. Apple recommends doing most of the interface work in this configuration, simply because it would mean less work for you.
⇨There are specifically 4 things you can change between size classes in interface builder:
1) Constraint constants          2) Fonts
3) Turning constraints on/off&nbsp4)Turning subviews on/off.
⇨The first two are pretty self explanatory, but let me show you how the last 2 work.
You can find how Turning constraints on/off from our previous post.
Now let's try forTurning subviews on/off.
⇨Make new single view application and name as SkipLayout and make sure the application is universal.
We are gone use Main.storyboard and will use 6 different views as shown below.
As you can see in image we have 6 views.
⇨Both top views has width:260 and height:160.And right view has X:20 and Y:20px and left view has X:310px Y:20 px.
⇨The 3 midle view has same width and height which is w:176 px and height : 160 px .The middle first view start at X:20 px and all 3 views have space between them which is 16 px. All 3 view's Y is 220 px.
⇨And the last bottom view has width:560 px and height:160 px. And it's position is X:20 px and Y:42 px.
If you run the application you will see that nothing looks good. I have run application in iphone 5. And if you run app in any simulator you will notice that nothing looks good.
You can see that everything is running out off size and the reason is that what we design is for a size class of wAny hAny .
You can find wAny hAny written at bottom of your story board as shown in below image.
If you click that you can see there are different size classes available there .
You can see its description in detail from my previous blog post.
And each of these classes has 3 possible values:
compact, regular, or any


⇨So now make sure you start with size class wAnyhAny. Because if you choose any other size class options then everything you do will apply to those devices with those size classe.
⇨So if you start with everything in compact width and compact height and then if you switch to ipad size then nothing will appear as you have design only for compact width and compact height. Not for other size classes.
⇨So now what we gone do is we apply constrains so when the device is resized or you gone say device has defferent sizes then these constrains will apply and know how these views will position.
⇨So first we all know that this all 6 views have same height . So we will select all views and go to Editor>Pin>Heights Equally. So no metter what the size changes all these has same height.

  Notice that below is look of storyboard.
⇨You can see that all constrains are showing in orange which means we haven’t provided enough information to constrains to size this items.
⇨So if you run again everything looks bad as contrains aren’t has enough information.We need to turn this constrains into blue so we have to provide enough information.
⇨We know that these top 2 has same width so we go to Editor>Pin>Width Equallly.
⇨We will do same for middle 3 views as they 3 are also same width.
⇨So now still we don’t have enough constrains as we didn’t provide information about leading or trailing space.
⇨So now we need to apply leading space to view and to apply that we have another option to apply constrains is that we control drag that view to the view with respect to whom we want to apply constrain.
⇨In our case control drag the top left view to main view and you will see there constrains in which select Leading space to container.

So we will do same for middle first view and also for bottom view.
Now we will do for top right view and fix its trailing space to container.
⇨We will do same trailing space to container for middle last view and bottom view.For middle view we are not gone a do leading or trailing space to container but we are gone position it to in relation to its siblings.
⇨So we are gone do is we are gone apply horizontal gap here.We are gone control drag top left view to top right view and select horizontal space between them as shown in image.

Now you can see that something is starting turning blue here.
Now we will do same for middle first view to middle view and also from middle view to middle last view.
Now we still don’t have info for Y- position so we need select top left view and control drag to container and select Top Space to Top Layout Guide
⇨Do same for top right view also.
⇨Do same for middle views but if you drag middle first view to top left view you will see vertical spacing option there and select that.
⇨For middle second view you can drag it to top left or top right any view.See below images.

Now for bottom view , first control drag it to middle first view and select vertical spacing then do control drag bottom view to middle second and third view and select same option.
Now we just need to give Bottom Space to Bottom Layout Guide for bottom view.
Now if you run the app you will see that it looks perfectly fine in all simulators in landscap and portrait mode.

Now Let's try option which is :
Turning subviews on/off
To do this first let's click on wAnyhAny you will see one popup like below.
The pop up is actually new size classes feature in ios 8 with Xcode6 as we know already. The value of this size classes is shown in below grid image.

⇨So this image is actually indicating that if we select grid which is wCompact hRegular our storyboard will now for iphone in portrait mode.
⇨That means whatever now we develop in this selected mode will only displayed in iphone portrait mode and if you run same app in ipad or run as iphone in landscape mode it will not displayed.
⇨This is classes as Turning subviews on/off. Let's try this using below steps:
⇨Select wRegular hRegular from size classes which is actually we have selected ipad in both landscape and portrait mode shown as below.
Because ipad has same size in landscape and portrait both mode.
Select wRegular hRegular from size Now take 1 label and name as Right and put that in bottom view at right size and take another label named as left and put it to left in bottom view.
Give constrains to Right label as trailing space and top space respective to bottom view and set it to size to fit content size from editor.
Now give constrains to Left label as Leading space and top space respective to bottom view and set it to size to fit content size from editor.


⇨Now if you run application in iphone you will see that in iphone in portrait and landscape both mode will see nothing but just 6 views. Left and right labels are not shown.
⇨Now if run app using ipad simulators you will see those labels in landscap and portrait both mode.
⇨Now you get to know how Turning subviews on/off works and also how size class works.


Now you can play with this as set one label in landscape mode of iphone and run application it will show in iphone in landscape mode only. Will not display in iphone in portrait mode or in ipad as well.
Hopefully this has helped you get a basic understanding of size classes and how they can greatly simplify your work in interface builder. For more practice of auto layout you can check post Practicing Auto Layout with an example

Wednesday 24 September 2014

Documenting your code with comments in Xcode 5

One of the nice new features introduced in Xcode 5 is the ability for source code comments to be used as documentation displayed in the Quick Help Inspector, in a Help Popup, and for Code Completion. I believe that this is made possible because Xcode now uses exclusively Apple’s own LLVM 5 compiler (GCC support has been removed), so it can build this functionality right in, since the compiler processes the comments along with user code. This kind of feature has long been available for users of other IDEs, such as Eclipse, and so this is a very welcome addition to Xcode, particularly as it might encourage developers to better document their code.
You can use either Doxygen or HeaderDoc format for the comments. As I come from a Java background I like to make the comments as close to JavaDoc as possible.

Here’s a simple example. This is a declaration for a utility method to check whether a file at a given URL has a newer time-stamp than another file at a given URL:
/**Check whether a file at a given URL has a newer timestamp than a given file.
Example usage:
@code
 NSURL *url1, *url2;
 BOOL isNewer = [FileUtils
 isThisFileNewerThanThatFile:url1 thatURL:url2];
@endcode
@see http://howtodoinios.blogspot.in for more information.
@param thisURL
The URL of the source file. 
@param thatURL
The URL of the target file to check.
@return YES if the timestamp of @c thatURL is newer than the timestamp of @c this URL , otherwise NO.
*/ 
+ (BOOL)isThisFileNewerThanThatFile:(NSURL *)thisURL thatURL:(NSURL *)thatURL;
In my configuration of Xcode it looks like this:

The comments sit right on top of the method declaration in the header file. There’s no point in putting them in the matching implementation file as we need these comments to be part of the public API. The comment opens with /** lock start and ends with a final */ block end. After the block start I’ve added a general description about what the method does. Then I’ve opened a @code tag and provided some code for example usage (this is a bit like the HTML tag). The @endcode tag closes it. Then I’ve added a @see tag which will appear as “See Also”. After this are the important tags used to document the two parameters and the return value. These are @param and @return . Note the @c tags in the “Returns” description which serve to display the following word using a monospaced font. Note that it’s important to save your source file in order for Xcode to detect a change to the file and regenerate the documentation from the comments. Now that this is done, if we select the method in the editor either here in the declaration, or as implemented, and then Option-Click on it we get the Help popup:

And it will also display in the Help Inspector:

And also will appear for Code Completion:


As a bonus, if we want to ensure that we get the spelling of the names of the parameters right, there’s even a project setting built into Xcode that will check and warn us:

Now, if I create a typo in the documentation I see this:
Clicking on the yellow triangle leads to a very helpful suggestion:
And that’s about it. A very nice and welcome addition to Xcode. Now that Apple is focussed on only supporting its own LLVM compiler in Xcode, I hope we’ll see more of these types of features in future versions.

Sunday 14 September 2014

Size Classes with Xcode 6: One storyboard for all Sizes Part - I

My favorite feature of Xcode 6 so far is the new size classes concept in Interface Builder.
Size classes are Apple's solution to the question "How can I easily work with so many different screen sizes and device orientations?" They also enable the condensing of universal apps into one storyboard file. Combined with the new adaptive view controllers, it's easier then ever to rely on interface builder, rather than fight with it, to simplify the creation of your app layouts.
⇨Every view controller in your app gets a trait collection object. This trait collection object has 2 size classes, a horizontal size class and a vertical size class.
⇨And each of these classes has 3 possible values:
compact, regular, or any.
These values can change based on the device and its orientation. Your app will layout its interface for each view controller based on the current size classes. Apple uses a grid to let the user choose which configuration to work in, so here's that same grid but with each device+orientation highlighted in its corresponding size class combo:
One interesting thing to note here: iPad has regular x regular for both landscape and portrait. Straight from Apple's 'What's new in iOS8 guide'
“With the amount of screen space available, the iPad has a regular size class in the vertical and horizontal directions in both portrait and landscape orientations.”
Ok, enough by-the-books stuff, lets open up Xcode 6 and try it out for ourselves.
⇨Create a new universal project for this demo. If you want to try it out in an existing Xcode 6 project, then you might have to explicitly enable size classes.
⇨You can do this in Interface Builder in the file inspector, right below the enable autolayout checkmark.
First, let's look at the size class grid in Xcode. This is the area where you can switch your storyboard between the different layout combinations. ⇨While viewing your storyboard, look towards the bottom and Click on the label that says "wAny hAny". You will see something that looks like the grid from the top of this post.
⇨By default, we start in our base configuration of any width and any height. Think of this as your master interface, things setup and changed here will be used by both the iPhone and iPad layout by default for all orientations.
⇨Apple recommends doing most of the interface work in this configuration, simply because it would mean less work for you.
⇨Let's layout a super-wide button in the center of the screen to play with. Give it a green background color so we can see its true size, center it vertically and horizontally with constraints:
⇨And give it a ridiculous fixed width of 600:
⇨Now run the app in both iPad and iPhone simulators. You will see it centered on both, but its clearly too wide for iPhone in both orientations.
⇨Let's use size classes to fix that. Go back to the grid and select the iPhone portrait config, compact width + regular height. Thats the red rectangle from the grid :
⇨You will notice that the bar you click on to access the grid changed from white to blue.
⇨This is basically just warning you: "Hey you're not in the base configuration anymore! Some changes you make here will only show when your app is running with these specific size classes.
⇨So now this bar is blue!" I say 'some' changes because there are specifically 4 things you can change between size classes in interface builder:
1) Constraint constants            2) Fonts
3) Turning constraints on/off    4)Turning subviews on/off.
⇨The first two are pretty self explanatory, but let me show you how the last 2 work.
Lets try turning a constraint off for the current size class
we are in (compact width and regular height).
⇨In the document outline, click on the Center X Alignment constraint we setup on our button:

⇨Now look in the attributes inspector, towards the bottom you will see the word installed with a checkmark next to it, and then a plus sign to the left of that.
⇨Click the plus sign and click "Compact Width | Regular Height (current)". You will now see 2 check marked items. Uncheck the one we just added (wC hR).
⇨Now our constraint is no longer installed and doing anything for this configuration of size classes.
⇨As you can see, Xcode is complaining that our constraints are too ambiguous, and if you run the app on an iPhone sim the button is no longer centered on the X axis.
⇨But running it on the iPad shows it still centered, because that constraint is still installed on our base configuration. It will be installed on every configuration except the one we just unchecked.
You can even rotate your iPhone sim and the button will magically go back to being centered, since iPhone landscape is a different size class config.
⇨Ok lets put the checkmark back in so the button goes back to being centered.
⇨Now lets change the constant we set for the buttons width. Select the button itself, and go to the Size Inspector and scroll to the bottom where all the constraints are. Click the Width Equals one and set it to 100:
⇨Run the app on the iPhone sim now, and you will see the button has the correct width for portrait iPhone. Running on the iPad sim shows the button 600 wide since we didn't change the width on our base config.
⇨However, it still doesn't look good on iPhone landscape, because iPhone landscape is still pulling from our base Any x Any configuration. Lets fix that.
⇨In the grid, select compact width and compact height. Thats the blue rectangle in our grid:
⇨Now change the width constant for this configuration the same way we did for compact x regular. Give it a width of 400.
⇨Running the app in iPhone and rotating to landscape causes the button to take a 400 width, which looks great (for our learning purposes). Whats nice is you can see a list of all the constants for each constraint for each different configuration.
⇨Just select the constraint you want to look at in the document outline, then go its its attribute inspector and they are all listed neatly below the original constant. It labels each one based on which configuration it applied on.
⇨What if we decided we wanted the button to disappear only when the iPhone was in landscape mode? Well with size classes we can uninstall views just like we uninstalled a constraint. Select our UIButton, scroll down to the very bottom of our attributes inspector, and add a new installed option for our current configuration by hitting the plus button, and then uncheck it.
⇨As you can see, the view instantly disappears from the storyboard because we uninstalled it on the configuration we are currently looking at. Running the app, you can see its gone in portrait iPhone, but it comes back when you rotate to landscape. And it will still be installed on the iPad since our iPad still uses the base configuration.
⇨The last thing I want to show is how we can be notified in code when these configurations are changed by something (usually a rotation).  Sizes classes are meant to replace the use of UIInterfaceOrientation & UIUserInterfaceIdiom, so its important to understand how to work with them in your code. 
⇨The first you will need to do is set your view controller(s) to conform to the UITraitEnviroment protocol:
class ViewController:UIViewControlle,UITraitEnvironment{
   override func viewDidLoad()
   {
     //code
   }
}
This protocol has a required method that notifies your view controller when the trait collection has changed:
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection!) {
        if previousTraitCollection? {
          //print out the previousTrait's info
        println(previousTraitCollection)
        }
    }
A UITraitCollection provides details about the attributes of a view controller. Heres what printing them out shows:

Those last two describe the vertical and horizontal size class of the trait collection we just changed from. Heres how that enum looks:
UIUserInterfaceSizeClass : Int {
     case : Unspecified
     case : Compact
     case : Regular
}
So now you know how turning a constraint off for the current size classes works.
Now Let's try another option which is : Turning subviews on/off You can find it in our next post from here Turning subviews on/off.
Hopefully this has helped you get a basic understanding of size classes and how they can greatly simplify your work in interface builder.

Sunday 25 May 2014

Improve Spotlight Searches with Search Operators in Mac OS X

If you know some specific attributes of a file, application, or item you are looking for on a Mac, you can use Spotlight Search Operators to dramatically narrow down your returned results in the OS X search feature. For example, if the file type of a document you are looking for is a PDF, you can pre-qualify search results by using operators to return only PDF’s within Spotlight. There are tons of search operators to use, and some can get very specific. Let’s jump into this a bit to learn more. Remember, to access Spotlight search on a Mac, hit the Command+Spacebar keys together. Then just type in the little popup search box to start narrowing down the queries and returned items.
Here are a some sample operators to enter before your search query that you can try yourself in Spotlight for Mac OS X:
Spotlight Search Operators
Note that all of these search operators are used in Spotlight in the following syntax format “operator:specific” always separated by a colon. If you’re having troubles with results coming back, check your syntax to make sure you have typed things correctly.
kind:application
kind:applications
kind:app
kind:contact
kind:contacts
kind:folder
kind:folders
kind:image
kind:images
kind:movie
kind:movies
kind:music
kind:audio
kind:jpeg
kind:pict
kind:text
kind:rtf
kind:pdf
kind:pdfs
kind:system preferences
kind:preferences
kind:bookmark
kind:bookmarks
kind:font
kind:fonts
kind:presentations
kind:presentation
kind:email
kind:emails
kind:mail message
kind:mail messages
kind:event
kind:events
kind:reminder
kind:reminders
The usage of this is demonstrated in the attached screenshot, where I pre-qualified my search for ‘screenshot’ with the jpeg file type operator, which led Spotlight to only search jpeg files for the search term.
More Specific Spotlight Search Operators
You can also get specific with operators by listing file types, kinds, and dates, like so:
kind:application
kind:pdf
kind:jpeg
kind:word
kind:folder
kind:image
kind:audio
date:today
date:yesterday

Find Files with Date Specific Searches in Spotlight for Mac OS X
What if you need to find files created or modified on a very specific date? There are a few ways to do this, but one of the fastest tricks is using date search operators in the Spotlight search menu of OS X.
For the unfamiliar, search operators are additional signals you can provide to Spotlight to help narrow down a search beyond just looking for a file or folder name. In this case, we’ll use date operators to find files based on the day when they were created or modified.

Search for Files Based on Creation Date in Spotlight
The simplest form of using the creation date modifier is to specify an exact date to Spotlight. To try this yourself, you’d want to hit Command+Spacebar to bring up the Spotlight search in OS X, then use the following search syntax:
created:xx/xx/xxxx
This will cause Spotlight to list all files created on the provided date.
For example, to find files that were created today  you’d use the following:
date:today
Spotlight will return the list of files, apps, documents, and folders created on that date, looking something like the following:


You can also provide additional operators to show files created before or after a specific date by using the < and > symbols, like so:
created:<08/12/2016
This can be used to modify the search query so that files created before < or after > a specified date are listed.
Another helpful trick can be searching for documents based on when they were modified, that is, when they were edited manually or modified by an app or file system.

Search for Files Based on Modification Date in Spotlight
To search for documents, files, or folders on the Mac that have been modified on a specific date, use the following search operator style in Spotlight. Again, hit Command+Spacebar to summon Spotlight and try the following type of search:
modified:xx/xx/xxxx
For example, to find files modified on May 14, 2014, you’d specify that date using the following (note if you use international date formats you’d want to adjust the query to accommodate that instead):
modified:05/14/2014
This will cause Spotlight to return everything that was modified on that specific date.
Remember, results returned through Spotlight can be cut and copied directly from the menu, which helps to make the Spotlight search tool basically an extension of the broader Mac file system. Additionally, you can modify the search priorities of Spotlight to list specific file types before others, which can further add to the usefulness of this trick and the Mac search feature in general.
So launch Spotlight and give it a test yourself to see how it works on your own Mac with your own files.
Try these Spotlight tricks out the next time you’re looking for files, documents, or apps created or modified on specific dates or before or after provided dates, you’ll be happy you did.