iOS

58 posts

XCODE IOS View Controller life cycle

View Controller call a series of methods before loading all the views and being ready for users to interact with them. The "viewDidLoad" method is invoked first. Inside it we should do any additional setup after loading the view, typically from a nib. There are other 4 commonly used methods that any iOS developer should know about: - (void)viewWillAppear:(BOOL)animated - (void)viewDidAppear:(BOOL)animated - (void)viewWillDisappear:(BOOL)animated - (void)viewDidDisappear:(BOOL)animated "viewWillAppear" is called when the view is about to made visible. Default does nothing. "viewDidAppear" is called when the view has been fully transitioned onto the screen. Default does nothing. "viewWillDisappear" is called when the view is dismissed, covered or otherwise hidden. Default does nothing. "viewDidDisappear" is called after the view was dismissed, covered or otherwise hidden. Default does nothing. There are situations when we need some specific things to be done, for example to save some data if the user quits the app, and these and some other ones are the places where she to insert that logic in our projects.

How to customize the NavBar in iOS

The NavBar or the navigation bar is the top side view that appears by default over our main view if we have a navigation controller presenting the corresponding view controller. Its dimensions for iPhone and iPod touch are 320 x 44, so if we want to set custom background images for that, we need 2 images: one normal of 320 x 44 pixels, and the other one for Retina Display, of 640 x 88 pixels. iOS provides us 4 default options for customising the NavBar, and we do that by writing the following line of code: self.navigationController.navigationBar.barStyle = UIBarStyleDefault; The "barStyle" property can be set to one of 4 values, which are: UIBarStyleDefault, UIBarStyleBlack, UIBarStyleBlackOpaque, UIBarStyleBlackTranslucent. Starting with iOS 5, it is very easy to set a background image for the NavBar in this way: UIImage *navBarImage = [UIImage imageNamed:@"nav-bar-image"]; [[UINavigationBar appearance] setBackgroundImage:navBarImage forBarMetrics:UIBarMetricsDefault];

How to create a navigation controller programmatically in iOS

The UINavigationController class implements a specialized view controller that manages the navigation of hierarchical content. This class is not intended for subclassing. Instead, you use instances of it as-is in situations where you want your application’s user interface to reflect the hierarchical nature of your content. This navigation interface makes it possible to present your data efficiently and also makes it easier for the user to navigate that content. To create a navigation controller programmatically, you have to write the following code: UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController]; Usually that is done in the "AppDelegate.m" file, but it can be done in any file you need. If you do that in the "AppDelegate.m" file than you should replace the line: self.window.rootViewController = self.viewController; with the following line: self.window.rootViewController = navController; and it is perfectly ok because UINavigationController is a subclass of UIViewController. If you run the program, you may notice a blue navigation bar appears on the top. You can customise that if you want, or you can hide it using any of the 2 lines below: navController.navigationBarHidden = YES; navController.navigationBar.hidden = YES; To set a title in the NavBar, you should write in the "viewDidLoad" method of the ViewController class that is currently displayed by the Navigator object, any of the 2 lines below: self.navigationItem.title = @"Title"; self.title = @"Title";

How to create view controllers programmatically in iOS

iew Controllers are special objects of UIViewController type or one of its subclasses. They connect the application's data and its visual appearance. Every-time the app shows something to the user, the displayed content is managed by a view controller or a group of view controllers coordinating with each other. The "Single View Application" template from Xcode comes with a default View Controller class, which also has a .xib file associated with it. If we have a look in the AppDelegate.m file, at the top, there is the "- (BOOL)application: didFinishLaunchingWithOptions:" method, and inside that, there is the following generated line of code (amongst others): self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; This creates a view controller object, initialising it with the "ViewController.xib" file, and then assigns it to the "viewController" property. There are situation when we have some ViewController class, but no .xib or .storyboard file associated with it. In that case we need to replace the line above with the following line of code: self.viewController = [[ViewController alloc] init]; and in the implementation file of our ViewController class, usually in the "- (void)viewDidLoad" method, we have to write all the UI creation and interaction code. For example: self.view.backgroundColor = [UIColor orangeColor];

Introduction to view controllers in iOS

View Controllers are special objects of UIViewController type or one of its subclasses. They connect the application's data and its visual appearance. Every-time the app shows something to the user, the displayed content is managed by a view controller or a group of view controllers coordinating with each other. iOS provides many view controllers classes for creating standard user interfaces, such as Navigation view controllers, and TabBar view controllers. Usually we subclass on of the standard view controllers, and create our custom ones to display content according to our needs. The UINavigationController takes care of navigation between 2 or more UIViewController objects. It takes care of placing the Back buttons on the Detail view controllers, and setting the title of that button with the text that was set as the title of the previous view controller. For more information, you can check the Apple's online Documentation at: http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007457-CH1-SW1

Working with UIPickerView class in iOS

The UIPickerView class implements objects, called picker views, that use a spinning-wheel or slot-machine metaphor to show one or more sets of values. Users select values by rotating the wheels so that the desired row of values aligns with a selection indicator. The UIDatePicker class uses a custom subclass of UIPickerView to display dates and times. To see an example, tap the add ("+") button in the the Alarm pane of the Clock application. The user interface provided by a picker view consists of components and rows. A component is a wheel, which has a series of items (rows) at indexed locations on the wheel. Each component also has an indexed location (left to right) in a picker view. Each row on a component has content, which is either a string or a view object such as a label (UILabel) or an image (UIImageView). For more information, you can check the Apple's online Documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPickerView_Class/Reference/UIPickerView.html

UIDatePicker customisation and IBAction methods

A UIDatePicker class allow us to customise the objects of its type. To do that, we have 4 options: UIDatePickerModeTime UIDatePickerModeDate UIDatePickerModeDateAndTime UIDatePickerModeCountDownTimer , which represent the values of an Enum type in the iOS SDK. Usually we do that in Xcode Interface Builder, if the date-pickers are created visually as well. When we interact with the UIDatePicker objects, we can call different event methods. The most common (which also comes as the default option when making the IBAction connection) is: "- (IBAction)datePickerValueChanged:(id)sender". If we want to get the value of the selected date and/or time from out picker in one of these methods, we can refer to the IBOutlet object or property if we have one, or we can change the parameter type from "id" to "UIDatePicker *", and then use the sender parameter-object (which is the actual UIDatePicker object). For more information, you can check the Apple's online Documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDatePicker_Class/Reference/UIDatePicker.html

How to create a UIDatePicker in iOS

There are some situation when we have to give the users the possibility to enter a date. He may input some invalid characters over there. Therefore, iOS SDK provides us a special class that enables us to choose a date from many options, and it is named UIDatePicker. Any object of this class has a special method "date", which by default returns the current date and time in the following format: YYYY-MM-DD hh:mm:ss +0000 We can format this output as we want, but this is the default one. We may use the UIDatePicker class to give different options to choose either date or time, as you will see in the next lessons, we can customise its appearance. For more information, you can check the Apple's online Documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDatePicker_Class/Reference/UIDatePicker.html

Working with UITableViewDelegate protocol in iOS

The delegate of a UITableView object must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions. Many methods of UITableViewDelegate take NSIndexPath objects as parameters and return values. UITableView declares a category on NSIndexPath that enables you to get the represented row index (row property) and section index (section property), and to construct an index path from a given row index and section index (indexPathForRow:inSection: method). Because rows are located within their sections, you usually must evaluate the section index number before you can identify the row by its index number. One very important method is: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath and it used in Master-Detail applications, where we have a Main/Master view which contains a basic table with general information about the items that we want to display, and when we click on any of the items, it takes us to a Detailed view, which contains all the info about the selected item. For more, please visit Apple's online documnation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html

How to create a custom cell programmatically in iOS

A cell in a UITableView is an object of UITableViewCell class, and can have one of four styles, which are: UITableViewCellStyleDefault, UITableViewCellStyleSubtitle, UITableViewCellStyleValue1, and UITableViewCellStyleValue2, and you can use those according to your app's specifications, or you can create your custom cells. In this video tutorial we will create a custom cell programmatically. For that we have to do most of our work in the "tableView:cellForRowAtIndexPath:" method. First we need a dataSource to populate the cell with info, so declare a private property for that, in the VieController.m file, just after the #import statement: @interface ViewController () @property (nonatomic, retain) NSMutableArray *dataSource; @end Then, in the viewDidLoad method allocate and initialise that: self.dataSource = [NSMutableArray array]; [self.dataSource addObject:[NSArray arrayWithObjects:@"20", @"JUN", @"7:00PM", @"Toyota Center", @"Houston, TX", @"FROM", @"$200", nil]]; [self.dataSource addObject:[NSArray arrayWithObjects:@"6", @"JUL", @"8PM", @"Frank Erwin Center", @"Austin, TX", @"FROM", @"$350", nil]]; In the "tableView:numberOfRowsInSection:" method return self.dataSource.count. In the "tableView:cellForRowAtIndexPath:" method write: // Each subview in the cell will be identified by a unique tag static NSUInteger const kDayLabelTag = 2; static NSUInteger const kMonthLabelTag = 3; // … and so on static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; UILabel *dayLabel; UILabel *monthLabel; // … and so on if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; cell.selectionStyle = UITableViewCellSelectionStyleNone; // Define the frames for each component of the Cell CGRect dayFrame = CGRectMake(5, 7, 64, 30); CGRect monthFrame = CGRectMake(5, 35, 64, 16); // … and so on // Adjust all the controls correspondingly dayLabel = [[UILabel alloc] initWithFrame:dayFrame]; dayLabel.tag = kDayLabelTag; dayLabel.font = [UIFont boldSystemFontOfSize:30.0f]; dayLabel.backgroundColor = [UIColor clearColor]; dayLabel.textColor = [UIColor darkGrayColor]; dayLabel.textAlignment = NSTextAlignmentCenter; monthLabel = [[UILabel alloc] initWithFrame:monthFrame]; monthLabel.tag = kMonthLabelTag; monthLabel.font = [UIFont boldSystemFontOfSize:16.0f]; monthLabel.backgroundColor = [UIColor clearColor]; monthLabel.textColor = [UIColor colorWithRed:0.0f/255.0f green:140.0f/255.0f blue:220.0f/255.0f alpha:1.0f]; monthLabel.textAlignment = NSTextAlignmentCenter; // … and so on // Add all created components to the new Cell [cell.contentView addSubview:dayLabel]; [cell.contentView addSubview:monthLabel]; // … and so on } else { // A reusable cell was available, so we just need to get // a reference to the subviews using their tags dayLabel = (UILabel *) [cell.contentView viewWithTag:kDayLabelTag]; monthLabel = (UILabel *) [cell.contentView viewWithTag:kMonthLabelTag]; } NSArray *cellInfoArray = [self.dataSource objectAtIndex:indexPath.row]; dayLabel.text = [cellInfoArray objectAtIndex:0]; monthLabel.text = [cellInfoArray objectAtIndex:1]; return cell;

Different types of UITableView cells in iOS

A cell in a UITableView is an object of UITableViewCell class, and can have one of four styles, which are: UITableViewCellStyleDefault, UITableViewCellStyleSubtitle, UITableViewCellStyleValue1, and UITableViewCellStyleValue2, and you can use those according to your app's specifications, or you can create your custom cells, which we will discuss later. All the cell styles (except UITableViewCellStyleDefault) allow us to specify a textLabel, and a detailTextLabel. We can also have an image on the left. For the right side, we can specify different accessory types, which are: UITableViewCellAccessoryNone, UITableViewCellAccessoryDisclosureIndicator, UITableViewCellAccessoryDetailDisclosureButton, and UITableViewCellAccessoryCheckmark. Each accessory type has its own meaning, and you have to check that in the Human Interface Guidelines provided by Apple. In case you use them for different meaning your app may get rejected. For more, please visit Apple's online documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html

Working with UITableViewDataSource protocol in iOS Part2

The UITableViewDataSource protocol is usually implemented by an ViewController class that mediates the application’™s data model for a UITableView object. The data source provides the table view object with the information it needs to construct and modify a table view. As a representative of the data model, the data source supplies minimal information about the table view’s appearance. The table-view object’s delegate—an object adopting the UITableViewDelegate protocol—provides that information. In the last video we've discussed about the required methods of the UITableViewDelegate protocol. There are also a couple of optional methods. For example in case of Grouped-Style table-views, we have sections, and each section may have a header and a footer. To specify how many sections a table view should have, we implement the following method: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; // 2 should be replaced with the number of sections we need } To specify the title of each section in a table view, we implement the following method: - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { NSString *titleOfSection; switch (section) { case 0: titleOfSection = @"First Section"; break; case 1: titleOfSection = @"Second Section"; // … and so on, depending how many sections we must have default: titleOfSection = @"No Title"; break; } return titleOfSection; } For more, please visit Apple's online documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html

Working with UITableViewDataSource protocol in iOS Part1

The UITableViewDataSource protocol is usually implemented by an ViewController class that mediates the application’™s data model for a UITableView object. The data source provides the table view object with the information it needs to construct and modify a table view. As a representative of the data model, the data source supplies minimal information about the table view’s appearance. The table-view object’s delegate—an object adopting the UITableViewDelegate protocol—provides that information. The two required methods of the protocol provide the cells to be displayed by the table-view as well as inform the UITableView, and they should look as below: - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 3; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } return cell; } We can also set the cell's properties, for example: cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row]; Many methods take NSIndexPath objects as parameters. UITableView declares a category on NSIndexPath that enables you to get the represented row index (row property) and section index (section property), and to construct an index path from a given row index and section index (indexPathForRow:inSection: class method). (The first index in each index path identifies the section and the next identifies the row.) For more, please visit Apple's online documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html

Working with UITableView objects in iOS

UITableView objects are commonly used in iOS development. There help us to represent data more clearly to the user, when we have more records that we want to display in a nice way. When we create a UITableViewController subclass in Xcode, it already contains a UITableView objects inside it. If we leave it as it is and run in the Simulator or on the device, we only get a blank table that we can scroll up and down (it doesn't contain any records because we did not tell it what data it should display and how to display that). Tables, in general, can contain any number of rows, but only ONE column. Each row is referred to as a CELL. There are 2 styles for table views - Plain and Grouped. In case we want to make more sophisticated tables, we must use custom cells for them, which we will discuss in later videos. You should check apps already made by other developers, to see when they use table view and how they resolve specific task using them. Some examples may be the Contacts and Notes apps.

Working with UIScrollView class in iOS

The UIScrollView class provides support for displaying content that is larger than the size of the application’s window. It enables users to scroll within that content by making swiping gestures, and to zoom in and back from portions of the content by making pinching gestures. UIScrollView is the superclass of several UIKit classes including UITableView and UITextView. The central notion of a UIScrollView object (or, simply, a scroll view) is that it is a view whose origin is adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the application’s main window. A scroll view tracks the movements of fingers and adjusts the origin accordingly. The view that is showing its content "through" the scroll view draws that portion of itself based on the new origin, which is pinned to an offset in the content view. The scroll view itself does no drawing except for displaying vertical and horizontal scroll indicators. The scroll view must know the size of the content view so it knows when to stop scrolling; by default, it "bounces" back when scrolling exceeds the bounds of the content. For more details, please visit Apple's Online Documentation at: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScrollView_Class/Reference/UIScrollView.html