After a month long break, today we will learn to create a login screen with animated button & transition in Swift using XCode 6.3 :

Animated Login Screen

Getting started

Open Xcode and create a new project by choosing the Single View Application template. Choose iPhone under “Devices”. Choose Swift as main language.

Templates

Next, you are presented with the page to set many of the important aspects of your project, particularly your “Product Name” and “Language”, which will be Swift, of course.

Product Name is pretty self-explanatory.  The organization name can be whatever you want, but it probably should the the company or name you are releasing your apps under.

The Organization Identifier is part of how your app will be referred to a bit more internally.  It is customary to use a reverse domain name of your company as the Organization identifier, so in my case my normal URL of “www.swiftyos.wordpress.com” should become “com.swiftyOS”.  You can see below it that the “Bundle Identifier” is created based on the product name and the organization identifier.  This is part of how your iOS device determines whether an update to your app is the same app or a new one, by checking this Bundle Identifier.

The Language box gives you the choice of Objective-C or Swift.  Of course for this blog, we’ll be choosing Swift for this box.  The next box has you select what devices this app should run on.  You have the choice of iPhone, iPad, or Universal.  Apple is heading more in the way of universal apps, so we’ll go with that for now (though this app will be designed for an iPhone, so it will look a bit silly on an iPad).  Finally you can click that checkbox if you want Xcode to get some Core Data code ready for you.  I don’t know enough about Core Data yet to really recommend whether or not to use this checkbox when using core data.  It would probably be best in the beginning at least not to, if only to let you see all of the moving parts of Core Data by having to set them up yourself.  After you learn though, I don’t know if it is better than doing it yourself or not.

When you click next, you will be presented with a save dialog, asking where you want to save your project.  Wherever you save it, a folder will be created with your app’s name, and inside will be the Xcode project, and a folder for each target your app has (which is going to be the app itself, and a test target right now).  You also have the option to create a Git repository for your project either locally or on a server.

After you click the “Create” button, the files for your project are generated and you are probably looking at your AppDelegate.swift file.

Adding custom files

This tutorial requires some custom class files to be imported into our project for the animation & transition to occur. These class files are made freely available to us by Takuya Okamoto on Github. You can download the class files from here. (Download Link). All credits go to Takuya for this wonderful animation class files. The download link mentioned above provides you with necessary Class files, Login & Home image files which we will use into our projects in future. Drag the folder & images into our Xcode project once downloaded.

The hierarchy for the project files should be as follows:

Hierarchy

Setting up the Storyboard

Now we’ll set up the storyboard.  In this app we will mainly focus on the animation of the login button and it’s custom transition to another view controller. So for the rest of items we will just use a background image for visual appearance along with a custom button. So the storyboard will need only a UIButton at the moment.

Open Main.storyboard and you will see a single ViewController which is all we need.

  1. Drag a UIButton and place it below the screen.
  2. Go to Identity Inspector & change the class to TKTransitionSubmitButton
  3. Change the title to Login.
  4. Add color & font as per your need.

The button placement will be somewhat like this:

Login Button

Connect the custom UIButton in the ViewController.swift file. Open the assistant editor, press ctrl + drag and create the outlet for the button named btnFromNib. Also add an Action for the Login button named onTapButton.

Outlet     Action

Setting up the ViewController code :

Open the ViewController.swift file and add some lines in the viewDidLoad function:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.       
        let bg = UIImageView(image: UIImage(named: "Login.png"))
        bg.frame = self.view.frame
        self.view.addSubview(bg)
        btnFromNib.layer.cornerRadius = 30.0
        self.view.bringSubviewToFront(self.btnFromNib)
        
    }

The code mentioned above creates a UIImageView programmatically named bg with UIImage named Login.png that we downloaded earlier. Then we set the frame of the UIImageView to the frame of the view itself so as to make the image fill the total screen size. We then add the subView bg to the main view. Next we change the corner radius of the UIButton btnFromNib that we created in Storyboard to a value of 30.0 & bring Subview to front of the screen.

We now need to add the UIViewControllerTransitioningDelegate to the ViewController class so that we can gain access to the transition delegate function and modify them. Add the delegate as follows: 

class ViewController: UIViewController, UIViewControllerTransitioningDelegate {

We then add the necessary delegate functions to our ViewController:

// MARK: UIViewControllerTransitioningDelegate
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return TKFadeInAnimator(transitionDuration: 0.5, startingAlpha: 0.8)
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return nil
    }

Here, the animationControllerForPresentedController returns a TKFadeInAnimator with custom duration & alpha values for the transition to another screen. While,  animationControllerForDismissedController returns nil since we don’t want anything to happen during dismissal.

Now create a new ViewController class file by pressing cmd + n.  CocoaTouch Class > Class name: SecondViewController & subclass of UIViewController.

SecondViewController

Let’s jump on to our button action in the ViewController and add some code:

button.animate(1, completion: { () -> () in
            let secondVC = SecondViewController()
            secondVC.transitioningDelegate = self
            self.presentViewController(secondVC, animated: true, completion: nil)
        })

The code above uses the inbuilt animate function for the object button and a completion block which presents the SecondViewController as well as sets the transition delegate to self.

That’s it for the coding part in ViewController file. Now move on to the SecondViewController which will be presented on login button press. Add the following lines of code:

override func viewDidLoad() {
        super.viewDidLoad()
        
        let bg = UIImageView(image: UIImage(named: "Home.png"))
        bg.frame = self.view.frame
        self.view.addSubview(bg)
        
        let tapRecognizer = UITapGestureRecognizer(target: self, action: "onTapScreen")
        bg.userInteractionEnabled = true
        bg.addGestureRecognizer(tapRecognizer)
    }
    
    func onTapScreen() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

The code presented above adds a custom bg UIImageView as we did earlier by setting the image name, frame to adding the subview. We then add a custom Tap Gesture Recognizer which detects a single tap on the screen to dismiss the view to login screen back programmatically. The onTapScreen function is the action for the tapRecognizer which uses dismissViewControllerAnimated to dismiss the view modally. The bg.addGestureRecognizer(tapRecognizer) adds tapRecognizer to the UIImageView.

Voila! we have just mastered using a custom animated button & transition. That’s all in this tutorial.

Running the App

So now you run the app with the big “Play” button in the top left of Xcode.  You then need to set what device to run the app on.  You can select a physical device (if you have a paid developer license).  Otherwise, or even just for simpler testing, you can run it in the simulator.  Choose the simulated device to run it on from the same menu.

Then wait a bit while the simulator loads.  Mine took about 30 seconds to load.  Then click on a cell and watch the magical wave transition occur!

Here is the source code on Github for the tutorial above !

I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don’t hesitate to contact me on Twitter @swifty_os, and I’ll see what I can do.  Thanks!

Advertisements