• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Xcode

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

Reduce the time taken for searching iOS documentation using Xcode

August 1, 2013 By Ravi Shankar Leave a Comment

This tip is for iOS developers who want to reduce the time taken while searching iOS documentation using Xcode. Documentation under the Xcode organiser window by default shows information on OS X as well. If you are not a Mac developer then you can turn off the documentation related with OS X.

Step 1: Launch Organizer window in Xcode and navigate to Documentation tab.

201308012017.jpg

Step 2: In the Documentation window, navigate to the Search Documentation option and click the arrow pointing downwards under the search icon.

201308012022.jpg

Step 3: Now select Show Find Options from the menu list.

201308012024.jpg

201308012025.jpg

Step 4: Navigate to the Find in list box then deselect “OS X 10.7 Core Library” and “OS X 10.8 doc set”.

This would exclude the OS X library while using the documentation search on Xcode.

Filed Under: Apple, Mac, Xcode Tagged With: Apple, Documentation, search, Xcode

Create an example iOS Project using Xcode

June 26, 2013 By Ravi Shankar Leave a Comment

We had already covered the basic overview of Xcode and now we are going see the steps required for creating an sample iOS Project that displays Welcome message on Xcode simulator.

Topics Covered

  1. Create New Project using Xcode.
  2. Add label control to Interface Builder.
  3. Edit label to add Welcome message
  4. Choose simulator in Xcode.
  5. Compile, Build and Run the project in Xcode.

Step 1: Launch Xcode then click FIle -> New -> Project.

201306251050.jpg

Step 2: In the Choose a template for your new project, pick Single View Application under the IOS section and click the Next button.

201306251052.jpg

Note :- We will cover the different templates in detail in future tutorials.

Step 3: Now in Choose options for your new project, enter the name for your project, organisation name and company identifier. In the Devices drop down select iPhone and mark the check box with caption as “Use Storyboards” and “Use Automatic Reference Counting” and click Next button.

201306251100.jpg

Some of the above terms like Storyboards, Automatic Reference Counting will be covered in future tutorials.

Step 4: Specify the location for creating this project and click the Create button.

201306251110.jpg  

Now a new project should be created and you should see a screen as shown below.

201306251115.jpg

Step 5: Select the MainStoryboard.storyboard in the Navigator Pane to access the Interface Builder.

201306251120.jpg

Step 6: Navigate to Utilities section and click Object tab. Scroll down and pick label control from the list then drag and drop the label on to Interface Builder.

201306251123.jpg

201306251123.jpg

Step 7: Edit the label and enter Welcome text.

201306251125.jpg

Step 8: Now select the iPhone simulator under Scheme section in Xcode toolbar.

201306251129.jpg

Step 8: Select Run option on Xcode toolbar or use the keyboard combination of command + R to run the sample project on Xcode simulator for iPhone. command + R will first compile and build the project before launching it on the simulator.

Filed Under: Apple, Develop, iPhone, Xcode Tagged With: Apple, iphone, Xcode

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

How to rename default view controllers in XCode

June 11, 2012 By Ravi Shankar Leave a Comment

Xcode by default provides default name for the view controllers depending upon on the selected projects templates. For example, while creating Tabbed Application, you will find FirstViewController and SecondViewController as the name for default view controllers.

NewImage

Now if you want to provide a proper name to the FirstViewControllers and SecondViewControllers you can use the Rename option available under the Edit menu.

To rename FirstViewController,  

Step 1: Navigate to FirstViewController.h and select the name after interface keyword.

NewImage 

Step 2: Click the Edit menu then Refactor and select Rename from the list of available option.

NewImage

Step 3: Enter the name then select Rename related files and click the Preview button. This would display the list of files and location where the rename would affect.

Step 4: If you are happy with Preview then save the changes.

NewImage

By this way you can rename the default view controller and their related files (.h, .m and XIB) in Xcode.

Filed Under: Xcode Tagged With: rename, view controllers, Xcode

XCode – Open file in same window on double click

June 2, 2012 By Ravi Shankar Leave a Comment

Xcode by default displays project file in a seperate window when the user double clicks on the file. And if you want to change this behavior and to open the file in the same window as that of single click then you can use the options provided as part of Xcode Preferences.

Step 1: Launch the XCode Preferences, XCode menu -> Preferences or ? + ,

Step 2: In the General tab, navigate to Double Click Navigation option.

XCode double click

Step 3: Select Same as Click value from the drop down list.

Now when a user double clicks on a file, XCode will display the file in the same window.

Filed Under: Xcode

  1. Pages:
  2. «
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. »
« 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