Friday, July 17, 2015

Displaying Game Centre Leaders board from Swift

In last post, I showed how we can authenticate local player and how we can post score to default leader board.

In this post, I will show how we can display leader board using swift gamekit API. Below code shows how we can display GKGameCenterViewController. Game center viewcontroller needs delegate, which is called when view is dismissed. Also we need parent viewcontroller which will be used to display GKGameCenterViewController.
func showLeaderboard(viewController: UIViewController, 
    gameCenterDelegate: GKGameCenterControllerDelegate) {
    let gameCenterVC: GKGameCenterViewController = GKGameCenterViewController();
    gameCenterVC.leaderboardIdentifier = defaultLeaderBoard;
    gameCenterVC.gameCenterDelegate = gameCenterDelegate;
    viewController.presentViewController(gameCenterVC, animated: true, completion: nil);
}
Now we have code that can display leader board, but we need to make our class conform to GKGameCenterControllerDelegate protocol and implement required method. Below is code for delegate method. Which simply dismiss presented view controller.
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) {
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
So, as you can see it's quite simple. Hope this will be helpful.

Friday, July 10, 2015

Creating array of IBOutlets of NSLayoutConstraint's from Swift in iOS

While working on my iOS app, I wanted to modify UI Constraint set from Interface Builder from Swift code.

Below video shows how we can create Array of IBOutlets using Interface Builder. Here I am creating array of NSLayoutConstraint, which I want to modify from Swift Code.



Now lets see how we can manipulate constraints from swift. First we need to define array of IBOutlet. Below code shows the same.
@IBOutlet var constraints: Array?
Now, once you connect IBoutlet from Interface Builder as shown in above video. You can use those. In below code I am modifying NSLayoutConstraint's constant value.
if( Utils.isIPad() ) {
    for constraint: NSLayoutConstraint in constraints! {
        if(Utils.isIPad()) {
            constraint.constant = 30
        }
    }
}
That's it, Thank you for reading.