Skip to main content

UITableView basic tutorial


In this tutorial we will create a table view with some dummy data, we will use disclosure indicator, change background color of cell, handle user selection, change separator color etc. There many tutorials which provides in depth information on UITableViews thus I will not touched that and instead targeted the practical How Tos.



Create a new single view project and add a UITableView to the initial view controller which has been added to the storyboard automatically.

In order to use UITableView in your viewcontroller you need to adapt to UITableViewDataSource and UITableViewDelegate. 

UITableViewDelegate provides us with methods which let us handle user selection events, define row height, modifying view and much more.

UITableViewDataSource provides data to UITableView to construct the view (to render content). Create table view cells, define the number of sections, number of rows in sections and much more.



Adapt to required protocols

@interface AYViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@end

Create dummy data

self.items = [[NSArray alloc] initWithObjects:@"First",@"Second",@"Third", nil];

Implement basic methods of the protocols we have adapted to

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ((self.items && [self.items count] > 0) ? [self.items count]: 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"AYBasicSampleCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.textLabel.text = [self.items objectAtIndex:indexPath.row];
    
    return cell;
}


Lets us run the application. BOOM!!!. I am not able to see anything in the table view. This is because we have not yet assigned a data source and delegate. 

Assign DataSource and Delegate for UITableView

In order to perform this let us create an IBOutlet for our UITableView first. Now, let us assign data source and delegate. 

self.sampleTableView.dataSource = self;
self.sampleTableView.delegate = self;

I have assigned them in viewDidLoad. Now, run your project again and now you will see dummy data on screen. WOW!!!




Its is working but we need to beautify it.

Add background color

In order to add background color add below mentioned code snippet in viewDidLoad.

self.sampleTableView.backgroundColor = [UIColor lightGrayColor];

Add round corner [Note: QuartzCore is needed for this]

Add QuarttzCore framework and then add QuartCore.h to the viewcontroller.


#import <QuartzCore/QuartzCore.h>

Now in viewDidLoad add following snippet.

self.sampleTableView.layer.cornerRadius = 10.0f;

Change separator color

In order to change separator color we need to use separatorColor property of UITableView.


self.sampleTableView.separatorColor = [UIColor grayColor];

Add a border to UITableView [Note: QuartzCore is needed for this]

self.sampleTableView.layer.borderColor = [UIColor grayColor].CGColor;
self.sampleTableView.layer.borderWidth = 1.0;

Change cell's text color

In order to change text color you need to update the cell creation code. We have created the cell in cellForRowAtIndex method. Use following snippet to change text color of cell.

cell.textLabel.textColor = [UIColor whiteColor];

Show Accessory Disclosure (Arrow at right)

In order to show accessory disclosure you need to set cell's accessoryType during cell creation in cellForRowAtIndex method.

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

Change accessory disclosure color

By default accessory disclosure will have black color. In order to change the color of accessory disclosure you need to initialize accessory view with an image.

cell.accessoryView = [[UIImageView alloc]
                           initWithImage:[UIImage imageNamed:@"ArrowWhite.png"]];

Let us see how does our table view look now:

 There is lot more to UITableView and in the next article in this series we will look into selection and navigating to different view controllers and more. Hope this post was of some help. Please share and provide your feedback.

Comments

Popular posts from this blog

Create a background / taskbar application in c# .NET

Recently, I was working on integration of two windows applications. First application will launch the second application on login and then they both will communicate using pre-defined set of instructions. There were some complications (I am not going into them) and thus we decided to have a third application which actually will act as mediator. First application will launch the mediator (third application) and it will launch the second application. For this purpose we needed to create a task bar application (which will run in background). How To ·          Create a new windows project and delete the default form (Form1). ·          In Program.cs create a new class and inherit it from Form. ·          Please refer the code below. ·          Now change the Main method. In Application.Run change the startup objec...

Check SQL Server Job status (State) using sp_help_job and xp_sqlagent_enum_jobs

This article is about checking the status of a SQL job. In our work place we have lot of SQL jobs. These jobs will run whole day and are business critical. They will load the data and generate extracts which will be used by business people. Thus, it becomes quite essential to support the system efficiently so that the job finishes in time and as desired. Also, while designing a new system sometimes we need to check the dependency of one job over another. In such scenario we need to check whether a particular job has finished or not. All this can be achieved in SQL Server by using the procedures:- sp_help_job xp_sqlagent_enum_jobs Note: xp_sqlagent_enum_jobs is an undocumented proc inside of sp_help_job and is used extensively to get SQL agent job information. sp_help_job: This procedure gives some insight into the status, and information, about a job. This stored procedure provides information such as last start time, job status etc. Syntax sp_help_job { [ @job_id= ] jo...

Java 8 JMX Default Metrics

This is more of a note. Here you can find default types and attributes for JMX on top of Java 8. Code: I will clean and explain it later :( private static void WriteAttributes(final MBeanServer mBeanServer, final ObjectName http) throws InstanceNotFoundException, IntrospectionException, ReflectionException { MBeanInfo info = mBeanServer.getMBeanInfo(http); MBeanAttributeInfo[] attrInfo = info.getAttributes(); System.out.println("Attributes for object: " + http +":\n"); for (MBeanAttributeInfo attr : attrInfo) { System.out.println(" " + attr.getName() + "\n"); } } Attributes for object: java.lang:type=MemoryPool,name=Metaspace:   Name   Type   Valid   Usage   PeakUsage   MemoryManagerNames   UsageThreshold   UsageThresholdExceeded   UsageThresholdCount   UsageThresholdSupported   CollectionUsageThreshold   Collectio...