• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

ios

Simple UITableView and UIAlertView example

January 9, 2014 By Ravi Shankar 1 Comment

In this article, we are going to see how to create a simple UITableView for displaying data. And display an alert on selection of any row using UIAlertView.

Launch Xcode, Click File > New Project and select Single View Application as the project template.

Choose a template for new new project

Enter the project details for Product Name, Organization Name, Company Identifier and Target device as iPhone.

201401091129.jpg

Then choose a location on your Mac to save the project.

201401091131.jpg

Navigate to Main.Storyboard and and delete the ViewController under View Controller Scene. Since we want a TableView, we are going to replace this View Controller with UITableViewController.

201401091134.jpg

Note :- We could have also used UITableView on top of View Controller but we will keep that for another session.

Now select UITableViewController from the Object library, drag and drop it on to the User Interface.

201401091141.jpg

Let us see the how to display list of values in the above table.

Navigate to ViewController.h in the Project Navigator and replace the following line

@interface ViewController : UIViewController

with

@interface ViewController : UITableViewController

Then use the Identity Inspector and specify the class for TableViewController as ViewController.

201401091146.jpg

Edit ViewController.m file and add a new instance variable and populate the cities in ViewDidLoad method.

@implementation ViewController

{

NSArray *cities;

}

– (void)viewDidLoad

{

[super viewDidLoad];

  

//Create the list of cities that will be displayed in the tableview

  

cities = [[NSArray alloc] initWithObjects:@”Chennai”,@”Mumbai”,@”New Delhi”, @”New York”, @”London”,@”Tokyo”,@”Stockholm”,@”Copenhagen”,@”Manchester”,@”Paris”,nil];

}

In the above code, cities is of type NSArray and it is initialised with set of values in the ViewDIdLoad method. These values will be displayed in the UITableView.

The ViewController will act as a delegate and datasource for the UITableViewController. These connections are automatically created and you can verify them by right clicking on the ViewController. If we had used UITableView instead of UITableViewController then these connections have to be made manually.

201401091202.jpg

The data for the tableview is provided by the following methods and these methods needs to be implemented in ViewController.m.

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

numberOfRowsInSection method is used for specifying the total rows in each section for the tableview. In this example, the UITableView has only one section for displaying the cities.

cellForRowAtIndexPath method is used for providing the data to each row in the TableView. The data is populated using the indexPath for each row.

Copy the method implementation to ViewController.m file

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [cities count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”Cities”];

  

cell.textLabel.text = [cities objectAtIndex:indexPath.row];

  

return cell;

}

The numberOfRowsInSection provides the tableview with the total count of rows i.e number of items in the cities array object. In the cellForRowAtIndexPath, we create a reusable UITableViewCell and assign the cities as per the row indexPath. Also make sure to specify the Identifier for prototype cell (User Interface) as Cities using the Attributes Inspector.

Now if you build and run the project, you should see a table with list of cities as shown below.

201401091307.jpg

Display the row selection using UIAlertView

Nothing will happen when you select any of the rows in the above table. Let us use the UIAlertView to display the row selection and for this we need to implement didSelectRowAtIndexPath in ViewController.m. Add the following didSelectRowAtIndexPath method implementation to the file.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *cityName = [cities objectAtIndex:indexPath.row];

  

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”City” message:cityName delegate:self cancelButtonTitle:@”Cancel” otherButtonTitles:nil, nil];

  

[alertView show];

}

The above code first retrieves the city name from cities array object using the row’s indexPath. In the second line, we create a instance of UIAlertView with title as “City”, selected city for the message attribute and provide the title for the cancel button. The delegate for UIAlertView will be ViewController and this specified by the delegate attribute. In the last line we use the show method to display the alert.

UITableView showing UIAlertView

Download the source code from here.

Filed Under: Develop, ios, iPhone, Programming, Xcode Tagged With: iOS, iphone, UIAlertView, UITableView, Xcode

How to add annotation to MapView in iOS

January 4, 2014 By Ravi Shankar 12 Comments

This article provides the steps for adding annotation to a MapView in iOS

Updated: – Click here for the updated article in Swift

Create a new Xcode Project – File > New > Project. Select the template for the project as Singe View Application under iOS > Application.

201401041109.jpg

Then provide the required details in the options for your new project screen.

201401041101.jpg

Select Main.storyboard file in the Navigator Area. This should display the User Interface in the Editor Area. Now select Map View from the Object Library, drag and drop it on the User Interface. Adjust the width and height of MKMapView to cover the ViewController.

201401041112.jpg

Now is if you try to Build and Run the project on iOS simulator, you will see the following errors message on the console window.

‘NSInvalidUnarchiveOperationException’, reason: ‘Could not instantiate class named MKMapView‘

This occurs when the MapKit library is not as part of the Link Binary with Libraries under Build Phases.

201401041121.jpg

Now add annotation, let us create a plist file containing array of locations with title, latitude and longitude.

Right click on the Project under the Navigator Area and select New File option.

201401041124.jpg

In the template for New File, select Property List under iOS > Resource section.

201401041127.jpg

Now provide name for the plist and save it under the Project directory.

201401041128.jpg

Now change the plist Root type to Array and start adding items of type Dictionary.

201401041129.jpg

The Dictionary item will contain title, latitude and longitude. As shown below, there are 6 items added to plist file.

201401041449.jpg

Create MapViewAnnotation class

In order display the location as annotation, we need to create custom annotation implementing the interface MKAnnotation.

201401041524.jpg

Create a MapViewAnnotation class subclassing NSObject

201401041526.jpg

Navigate to MapViewAnnotation.h header file and replace the content with the following

#import <Foundation/Foundation.h>

#import <MapKit/MapKit.h>

@interface MapViewAnnotation : NSObject <MKAnnotation>

@property (nonatomic,copy) NSString *title;

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate;

@end

Now navigate to MapViewAnnotation.m header file and replace the content with the following.

#import “MapViewAnnotation.h”

@implementation MapViewAnnotation

@synthesize coordinate=_coordinate;

@synthesize title=_title;

-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate

{

self = [super init];

_title = title;

_coordinate = coordinate;

return self;

}

@end

 

The above code creates a title and coordinate property and these properties are initialised in the implementation class using the initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate method.
Creating and adding annotation to the MapView
Create a IBOutlet property to MKMapView and connect the outlet the MapView in the User Interface. After adding the IBOutlet, the ViewController should look like this

#import <UIKit/UIKit.h>

#import <MapKit/MapKit.h>

@interface ViewController : UIViewController

@property (nonatomic,strong) IBOutlet MKMapView *mapview;

@end

Navigate to ViewController.m and add new method createAnnotations for creating the annotation from the plist and loading the annotation to the map view.

– (NSMutableArray *)createAnnotations

{

NSMutableArray *annotations = [[NSMutableArray alloc] init];

//Read locations details from plist

NSString *path = [[NSBundle mainBundle] pathForResource:@”locations” ofType:@”plist”];

NSArray *locations = [NSArray arrayWithContentsOfFile:path];

for (NSDictionary *row in locations) {

NSNumber *latitude = [row objectForKey:@”latitude”];

NSNumber *longitude = [row objectForKey:@”longitude”];

NSString *title = [row objectForKey:@”title”];

//Create coordinates from the latitude and longitude values

CLLocationCoordinate2D coord;

coord.latitude = latitude.doubleValue;

coord.longitude = longitude.doubleValue;

MapViewAnnotation *annotation = [[MapViewAnnotation alloc] initWithTitle:title AndCoordinate:coord];

[annotations addObject:annotation];

}

return annotations;

}

In the above method, we read the locations from the plist file. Then create CLLocationCoordinate2D for each location using the latitude and longitude details. These details are then used for creating the MapViewAnnotation object.
In the ViewDidLoad method, load the annotations to the MapView by calling createAnnotations method.

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

[self.mapview addAnnotations:[self createAnnotations]];

}

If you try to build and run the project, these annotations will not be displayed as the map is not zoomed to these locations. You can fix by adding the following zoomToLocation method.

– (void)zoomToLocation

{

CLLocationCoordinate2D zoomLocation;

zoomLocation.latitude = 13.03297;

zoomLocation.longitude= 80.26518;

MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 7.5*METERS_PER_MILE,7.5*METERS_PER_MILE);

[self.mapview setRegion:viewRegion animated:YES];

[self.mapview regionThatFits:viewRegion];

}

The above code, creates coordinate for the zoom location. Then we define MKCoordinateRegion and set that as the region for the map view. The METERS_PER_MILE is a constant with the value as 1609.344 which needs to be added after the @implementation ViewController

#define METERS_PER_MILE 1609.344

Now you be able to compile and run the project and you should be able to see the following in iOS simulator. And selecting any annotation, should be display the title.

201401041644.jpg

201401041645.jpg

 

Download the source from here

Filed Under: ios, Xcode Tagged With: Annotations, iOS, MapKit.framework, MKMapView, Xcode

How to change page scaling in Xcode

August 15, 2013 By Ravi Shankar Leave a Comment

Xcode provides option to increase or decrease the page scaling. This page scaling option is available as part of the Page Setup. This feature is quite useful when you want reduce the number of pages used for printing any Objective-C code.

201308152115.jpg

The default page scale is set to 100% and you can change this by following the below mentioned steps.

Click File menu and select Page Setup from the menu list.

201308152110.jpg

This should display the following Page Setup screen.

201308152112.jpg

Navigate to the Scale option and change the default value from 100% to say 50%. Then click OK button to confirm and save the changes. Now when you go to print preview screen (Xcode File menu -> Print), you should notice the effect of reduced Scale changes.

201308152118.jpg

Filed Under: Apple, Develop, ios, Xcode Tagged With: Apple, page scale, page setup, Print, Xcode

What is Delegation in iOS ?

August 15, 2013 By Ravi Shankar Leave a Comment

Delegation is one of the commonly used pattern in iOS. This is used tell an object to act on behalf of another. Refer to Apple documentation for detailed information on delegate pattern. Let us see this with an example program that uses UITextFieldDelegate.

This is a SingleView Project with one UITextField control.

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

UITextField *tfMessage1= [[UITextField alloc] initWithFrame:CGRectMake(50, 80, 250, 150)];

tfMessage1.borderStyle = UITextBorderStyleRoundedRect;

[self.view addSubview:tfMessage1];

}

– (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

Now if you run the project using Xcode simulator, the UITextView will be displayed. You can type in the UITextField but when pressing Return on the keyboard will do nothing. By using delegate pattern we are going to tell UIViewController to process the pressing of the return button on behalf of UITextField and hide the keyboard.

Step 1: Open the ViewController.h file and implement the UITextViewDelegate as shown below.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

@end

Step 2: Navigate to viewDidLoad method in implementation file, add “self.tfMessage1.delegate= self” as shown in the below code snippet.

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

UITextField *tfMessage1= [[UITextField alloc] initWithFrame:CGRectMake(50, 80, 250, 150)];

tfMessage1.borderStyle = UITextBorderStyleRoundedRect;

[self.view addSubview:tfMessage1];

tfMessage1.delegate = self;

}

This makes the UIViewController to act on behalf of UITextField.

Step 3: Now implement the following method that would process the “Pressing of return” key.

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

[textField setUserInteractionEnabled:YES];

[textField resignFirstResponder];

return YES;

}

Filed Under: Apple, Develop, ios Tagged With: Apple, delegate pattern, delegation, Objective C

Different ways to connect IBAction to UIButton

August 13, 2013 By Ravi Shankar 2 Comments

In this tutorial, we are going to see the different ways for connecting IBAction to UIButton. Let see this with an example that displays an alert message on the touch event of UiButton.

Method 1 (Assistant Editor):

Step 1: Drag and drop Round Rect Button from the Objects library on to Interface builder.

Step 2: Now click the Show Assistant Editor option on Xcode toolbar. This should display the Interface builder and code editor adjacent to each other as shown below.
201308130927.jpg
Step 3: Select the button on Interface builder then hold control key on keyboard and drag the line to the editor window (.h file).

201308130937.jpg
You should notice Insert Outlet, Action or Outlet Collection entry as shown in the above screenshot. Selecting the option would display a window for defining the IBAction.
201308130943.jpg
Step 4: Select “Action” for Connection, provide a name (e.g.:- showAlert), Event as “Touch Up Inside” then click Connect. This should add a new IBAction entry in the header and implementation file.

Header file (.h)
201308130949.jpg
Implementation File (.m)
201308130951.jpg
Step 5 : Now add the following UIAlertView code inside the showAlert method in implementation file.

  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Demo” message:@”IBAction Demo” delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];

  [alertView show];

201308130953.jpg

Executing the project in the simulator should display the following alert on tapping the Button.

201308130956.jpg

Method 2 (Connections Inspector) :

Step 1: Drag and drop a Round Rect Button on to the Interface builder.

Step 2: Navigate to implementation file and add the following IBAction code for displaying the Alert.

201308131002.jpg

Step 3: Open nib file, navigate to Show Connections Inspector option available on the left hand side.

201308131000.jpg

Selecting the File Owner’s option should display the details in the Connections Inspector. This should display the IBAction method under the Received Actions section.

201308131006.jpg

Step 4: select showAlert and drag it to the UIButton on the Interface builder.

201308131009.jpg

Releasing the mouse click should display the following Events list. Select Touch Up Inside from the list.

201308131011.jpg

Once connected, you should see the connection between the IBAction method and the control under Received Actions.

201308131012.jpg

Method 3 (Programmatically):

Step 1: Launch the implementation file for adding the Round Rect Button Programmatically.

Step 2: Add the IBAction showAlert method with the following alert message.

  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Demo” message:@”IBAction Demo” delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];

  [alertView show];

201308131002.jpg

Step 3: Navigate to ViewDidLoad Method and add the following code to instantiate UI button and connect button to Touch Up Inside event with showAlert method.

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

  

UIButton *btnDemo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // Create Round Rect Type button.

btnDemo.frame = CGRectMake(100, 100, 100, 100); // define position and width and height for the button.

[btnDemo setTitle:@”Show Alert” forState:UIControlStateNormal];

  

//connect the showAlert method with button target attribue. Also spectify when (event) you want to call

//this methid

[btnDemo addTarget:self action:@selector(showAlert:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btnDemo];

}

Filed Under: Apple, Develop, ios Tagged With: Apple, IBAction, UIButton

XCode’s iOS Simulator for iPhone and iPad

March 2, 2013 By Ravi Shankar Leave a Comment

iOS Simulator in Xcode can be used for testing iOS apps before trying the apps on a live device. Listed below are the different settings and features on iOS Simulator.

Launching iOS Simulator

iOS Simulator can be launched by executing Program on Xcode

Run Program on Xcode : Keyboard Shortcut is Command + R, Menu is Product -> Run

The screenshot of IOS Simulator is shown below.

201303021038.jpg

Another alternate way to launch the iOS Simulator is by using the menu option under

Xcode -> Open Developer Tool -> IOS Simulator

201303021039.jpg

iOS SDK Version

IOS SDK version of iOS Simulator can be determined by clicking the Hardware menu -> Version

201303021112.jpg

Deleting Apps and Settings

Reset Content and Settings option clears all the apps and settings from the simulator. For example if you have changed the app icon, the new icon will not be displayed unless you delete the app from the simulator and re-run the program.

201303021133.jpg

You can also delete individual apps by clicking and holding the installed apps followed by clicking delete mark just like you do on any iOS device.

201303021135.jpg

Choosing the device screen on Simulator

IOS Simulator allows users to choose different device screens such as iPad, iPad (Retina), iPhone, iPhone (Retina 3.5 inch) and iPhone (Retina 4 inch). You can choose the desired screen by navigating to Hardware menu option and selecting the Device.

201303021206.jpg

It is always recommend to try out the apps on the different device simulator before releasing it on the App Store. For example if you are developing an app for the iPhone then you need to try out in all the 4 iPhone device simulator apart from testing your app on live device.

Taking App Screenshots using Simulator

IOS Simulator can be used for taking screenshots of your app for publishing app on the App Store. This is quite useful when you do not have all IOS devices but still want to see the screenshots of your app. The Screenshots can be taken by loading the app on the Simulator and clicking the File menu -> Save Screenshot. The screenshot will be saved to your desktop in .PNG file format.

201303021146.jpg

IOS Simulator also provides option to copy the individual screen from the simulator using the option available as part of the Edit menu.

201303021200.jpg

Other Hardware features

IOS Simulator has features that lets users to see the behaviour of the app on each action such as Rotating Screen to Left, Rotating the Screen to Right, Shake Gesture, Accessing the Home Screen, Locking the Device and also simulating low memory warning.

201303021214.jpg

Simulate Locations

Location menu option under the Debug menu is quite useful for development of location based apps. This lets developers to simulate location required for testing their app.

201303021218.jpg

iOS Simulator Screen Zooming

IOS Simulator screen size can be increased and decreased based on your need using Window -> Scale menu option.

201303021222.jpg

Filed Under: Apple, Develop, ios, iPad, iPhone, Xcode Tagged With: Apple, iOS Simulator, iphone

Provisioning iPhone 4S for deploying and testing Apps

March 31, 2012 By Ravi Shankar 1 Comment

Listed below are detail steps for provisioning iPhone 4S for deploying and testing Apps. The steps have been broadly classified in to the following topics.

  • Requesting Development Certificate
  • Submit Certificate in iOS Provisioning Portal
  • Installing Certificate
  • Registering Device to Provisioning Portal

Requesting Development Certificate

Requesting development certificate requires you to generate a Certificate Signing Request (CSR). The CSR can be generated using the KeyChain app available as part of the Mac OS. You can quickly launch keychain using spotlight search. Apart from generating the CSR, the Keychain app also generates the public and private key.

201203311214.jpg

Select Keychain Access preferences from the menu list and navigate to Certificates tab.

201203311227.jpg

Turn off the Online Certificate Status Protocol (OCSP).

201203311229.jpg

Now to request Certificate, click the Keychain Access menu, select Request a certificate from a Certificate Authority under the Certificate Assistant.

201203311244.jpg

In the Certificate Assistant window, enter your email address, name and mark the radio option with caption as Saved to disk also the check box with label as Let me specify key pair information.

201203311250.jpg

Save the generated certificate to your desktop.

201203311318.jpg

Then for the Key Pair information, select Key Size as 2048 bits and Algorithm as RSA.

201203311319.jpg

On clicking the continue button will display the following confirmation message.

201203311439.jpg

The login section under Keychain Access would display the generated Public key and Private key.

201203311440.jpg

Submitting Request in Provisioning Portal

Login to the members account with your Apple user id and password. Click the iOS Provisioning Portal link available under Developer Program Resources section.

201203311444.jpg

In the Provisioning Portal, navigate to Certificates section and click the Request Certificate button under Development.

201203311443.jpg

This would display a screen with option to submit the CSR.

201203311446.jpg

Choose the required CSR and click the Submit button. After submitting the status would initially be displayed as Pending issuance and later a download link would appear.

201203311447.jpg

201203311448.jpg

Now install the WWDR certificate and iOS developer Certificate on your Mac system

201203311449.jpg

201203311450.jpg

You can verify the installation of certificates by navigating to My Certificates in Keychain Access App.

201203311451.jpg

Registering Device to Provisioning Portal

You can use Xcode for registering the Device ID and this process also create the App ID. Launch Xcode, click the Window menu option and select Organizer from the menu list.

201203311454.jpg

This would display the list of available Devices that have been connected to the Mac system,

201203311455.jpg

When the device is connected, a green status light will be displayed. Now select iPhone 4S and click the Use for Development button. If your Device and Mac system are out of sync with the iOS SDK then you will get the message to keep both of them in sync.

201203311501.jpg

Once the device and Mac system are in sync, you can add the device to Provisioning Portal by right clicking on the device and selecting Add Device to Provisioning Portal.

201203311503.jpg

Xcode will request permission for accessing your Keychain, click Always Allow button and sign-in with your Apple Developer Account credentials. Also allow code sign to sign using your key in keychain.

201203311506.jpg

Now you can test your app on iPhone 4S by selecting the device from Active Scheme list.

201203311508.jpg

Filed Under: Develop, ios Tagged With: Apple, Blogging, deploying, iphone, Provisioning

Code Example – Check for Prime Number Objective C

February 10, 2012 By Ravi Shankar 1 Comment

This is a simple Objective C program written to check whether a number is a Prime number.

//

// main.m

// PrimeNumbers

//

// Created by Ravi Shankar on 10/02/12.

// Copyright (c) 2012 rshankar.com. All rights reserved.

//

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

{

@autoreleasepool {

  

int number;

BOOL isPrime=YES;

NSLog (@”Enter a number”);

scanf(“%i”,&number);

for (int i=2; i < number –1; i++)

{

if (number % i == 0)

{

isPrime = NO;

break;

}

}

if (isPrime)

{

NSLog (@”%i is a Prime Number”,number);

}

else

{

   NSLog (@”%i is not a Prime Number”, number);

}

  

}

return 0;

}

Output (as displayed in Xcode console window)

2012-02-10 15:53:52.072 PrimeNumbers[1164:707] Enter a number

23

2012-02-10 15:53:58.665 PrimeNumbers[1164:707] 23 is a Prime Number


2012-02-10 15:54:41.469 PrimeNumbers[1176:707] Enter a number

24

2012-02-10 15:54:44.589 PrimeNumbers[1176:707] 24 is not a Prime Number


This program checks whether the number is divisible by any of the n-1 number and if divisible (% operator returns reminder as 0) then the flag is set to false otherwise it is set to true. Then based on the flag value the message is printed to the console window.


Filed Under: Blogging, Develop, ios Tagged With: Objective C, prime number, Program

  1. Pages:
  2. «
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. 9
  12. 10
  13. »
« Previous Page
Next Page »

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy