`
zl4393753
  • 浏览: 333225 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Creating a custom Table View Cell programmatically

 
阅读更多
start open xcode and create a new project, chose the template as “Navigation Based” and name it as “CustomCellTestProject”. What template you chose does not matter, refer my previous posts to find how you can start working on any template.
First thing we will do is create a customCell. Right click on Classes and add a new UITableViewCell subclass. Name it as “CustomCell”. Now open CustomCell.h and add the following code:
#import
@interface CustomCell : UITableViewCell {
 UILabel *primaryLabel;
 UILabel *secondaryLabel;
 UIImageView *myImageView;
}
@property(nonatomic,retain)UILabel *primaryLabel;
@property(nonatomic,retain)UILabel *secondaryLabel;
@property(nonatomic,retain)UIImageView *myImageView;
@end


We create the three elements and added them to the contentView of our cell.
synthesize all the three elements in CustomCell.m as we are going to access these elements from other classes.

@synthesize primaryLabel,secondaryLabel,myImageView;


Here we have simply added a primary label to display the primary text, a secondary label and an imageView. These elements will be created and added into the content view of our custom cell. So open CustomCell.m and add the following code

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Initialization code
 primaryLabel = [[UILabel alloc]init];
 primaryLabel.textAlignment = UITextAlignmentLeft;
 primaryLabel.font = [UIFont systemFontOfSize:14];
 secondaryLabel = [[UILabel alloc]init];
 secondaryLabel.textAlignment = UITextAlignmentLeft;
 secondaryLabel.font = [UIFont systemFontOfSize:8];
 myImageView = [[UIImageView alloc]init];
 [self.contentView addSubview:primaryLabel];
 [self.contentView addSubview:secondaryLabel];
 [self.contentView addSubview:myImageView];
 
}
return self;
}


Now, we have already added the UI elements into our cell but you must have noticed, we have not yet defined how these elements will appear inside cell. Go ahead and add the following code for that:

- (void)layoutSubviews {
[super layoutSubviews];
 CGRect contentRect = self.contentView.bounds;
 CGFloat boundsX = contentRect.origin.x;
 CGRect frame;
 frame= CGRectMake(boundsX+10 ,0, 50, 50);
 myImageView.frame = frame;
 
 frame= CGRectMake(boundsX+70 ,5, 200, 25);
 primaryLabel.frame = frame;
 
 frame= CGRectMake(boundsX+70 ,30, 100, 15);
 secondaryLabel.frame = frame;
}


You can do anything in this method to define the lay out of cell. I have simply assigned frames to all the elements.
You can also find a method in CustomCell.m

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}


This method can be used to define how your cell should react when it is selected. You can describe what should be the highlight color or may be you want to flash one of the labels anything of your choice. I am leaving this method as it is.
We are done with creating our custom cell and now we have to use it. Open RootViewController.m and import CustomCell.h at the top.

#import “CustomCell.h”


I am going to create 5 cells here, you can just use your own logic of specifying number of cells and data. So change the following method to look like this:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}


Now we are going to use our custom cell. If you look at the cellForRow method, you will find that a UItableViewCell has been created and re used. Now all we have to do is to replace this cell with our new cell. Change the code inside this method to look like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @”Cell”;
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
 
// Set up the cell…
 switch (indexPath.row) {
 case 0:
 cell.primaryLabel.text = @"Meeting on iPhone Development";
 cell.secondaryLabel.text = @"Sat 10:30";
 cell.myImageView.image = [UIImage imageNamed:@"meeting_color.png"];
 break;
 case 1:
 cell.primaryLabel.text = @"Call With Client";
 cell.secondaryLabel.text = @"Planned";
 cell.myImageView.image = [UIImage imageNamed:@"call_color.png"];
 break;
 case 2:
 cell.primaryLabel.text = @"Appointment with Joey";
 cell.secondaryLabel.text = @"2 Hours";
 cell.myImageView.image = [UIImage imageNamed:@"calendar_color.png"];
 break;
 case 3:
 cell.primaryLabel.text = @"Call With Client";
 cell.secondaryLabel.text = @"Planned";
 cell.myImageView.image = [UIImage imageNamed:@"call_color.png"];
 break;
 case 4:
 cell.primaryLabel.text = @"Appointment with Joey";
 cell.secondaryLabel.text = @"2 Hours";
 cell.myImageView.image = [UIImage imageNamed:@"calendar_color.png"];
 break;
 default:
 break;
 }
 
return cell;
}


I have added some dummy data. You can use your data source to provide data for primaryLabel and secondaryLabel. Please note that I have used three images here. You can use any image of your choice. All you need to to do is copy the images and paste it into your project root folder (which in this case is CustomCellTestProject folder). After pasting the files, in xcode right click on Resources (or any group), select Add >> ExistingFiles and then select all the images you want to add in you project. Once added you can simply use them by their names.
Thats it, go ahead and run the project. You will find something wrong when you compare you simulator screen with mine. If you noticed in the CustomCell.m, I have given some frames to the UI elements. You need to make sure that the height of your cell large enough to accomodate all the elements. So add this following code and you fixed the issue:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 return 50;
}

分享到:
评论

相关推荐

    Joomla! 1.5 Development Cookbook.pdf

    Installing a plugin programmatically during a component installation 240 Managing categories the easy way 243 Defining JParameters using XML 245 Creating a JParameter object 247 Rendering a ...

    Drupal.8.for.Absolute.Beginners.1430264667

    Chapter 11: Creating a Drupal Block Programmatically and Basic MySQL Usage Chapter 12: Theming Your Site Part 1: Theme Functions and a Twig Primer Chapter 13: Theming Your Site Part 2: Creating a ...

    VB.NET Developer's Guide(4574).pdf

    Exercise 8.1:Creating a Custom Windows Component 399 Creating Custom Windows Controls 403 Exercise 8.2:Creating a Custom Windows Control 404 Summary 407 Solutions Fast Track 407 Frequently Asked...

    Professional C# 3rd Edition

    Creating a Windows Form Application 574 Control Class 579 Size and Location 580 Appearance 580 User Interaction 580 Windows Functionality 582 Miscellaneous Functionality 582 Class Hierarchy 582 ...

    Professional.MFC.with.VC6

    Programmatically Creating Data Sources Other Interesting Settings Your Environment Data Definition Language Commands CDatabase and CDaoDatabase Opening DAO Databases Connection Settings SQL ...

    Learning iOS Programming, 2nd Edition.pdf

    After discussing the table view controller in detail, we discuss some of the other view controllers and classes that will become useful when building your applications: simple two-screen views, single...

    iOS 人机交互指南(iOS Human Interface Guidelines)

    Table View 113 Text View 121 Web View 122 Container View Controller 123 Alerts, Action Sheets, and Modal Views 123 Alert 123 Action Sheet 127 Modal View 130 Controls 133 Activity Indicator 133 Date ...

    sharpPDF2_0beta源码

    PDFsharp is a .NET library for creating and modifying Adobe PDF documents programmatically from any .NET language like C# or VB.NET. PDFsharp defines classes for the objects found in PDF files, so you...

    Localizing Windows Forms programmatically using a VS2010 Add-in

    能够将整个project 中form 的 localizable 设置为true,也可以批量更改form 的属性。 下载完毕之后,将文件解压到E盘,然后,在visual studio 2010 的 tools 下面选择“options” ->“Add-in/Macros Security" 点击...

    Servlets和JSP核心技术 卷2(英文版) 第一部分

    Servlets和JSP核心技术 卷2 内容还是很详细的,看过卷1的人可以继续用这本书深造,呵呵 目录: Chapter 1....Section 1.1....Section 1.2....Section 1.3.... Example: Creating a Web Application WAR File Index

    Servlets和JSP核心技术 卷2(英文版) 第二部分

    没办法,文件超出上传20M限制 Servlets和JSP核心技术 卷2 内容还是很详细的,看过卷1的人可以继续用这本书深造,呵呵 目录: Chapter 1.... Example: Creating a Web Application WAR File Index

    Programmatically Setting Control Adapters for URL Rewriting and AJAX

    Programmatically Setting Control Adapters for URL Rewriting and AJAX。

    Introduction.to.Android.Application.Development(4th,2013.12) pdf

    Creating a Launch Configuration for Your Project 75 Running Your Android Application in the Emulator 76 Debugging Your Android Application in the Emulator 80 Adding Logging Support to Your Android ...

    Unity.in.Action.Multiplatform.Game.Development.in.Csharp

    Loading images programmatically 104 ■ Setting the image from an invisible SceneController 105 ■ Instantiating a grid of cards 107 ■ Shuffling the cards 109 5.4 Making and scoring matches 110 ...

    DevExpress VCL 12.2.6(v2012vol2.6) 源码-例子-帮助-part1

    Q373762 - Ribbon Form - Restoring down a minimized application incorrectly resizes the Windows Aero Glass frame after the Ribbon form was programmatically hidden when minimizing the application ...

    DevExpress VCL 12.2.6(v2012vol2.6) 源码-例子-帮助-part2

    Q373762 - Ribbon Form - Restoring down a minimized application incorrectly resizes the Windows Aero Glass frame after the Ribbon form was programmatically hidden when minimizing the application ...

    Visual C++ 编程资源大全(英文源码 控件)

    (23KB)<END><br>16,custlist.zip CUSTLIST shows how to use custom draw in a list view control. (23KB)<END><br>17,div.zip This sample shows how floating-point exceptions may be captured and ...

    StripedProcessButton Android库.zip

    Library for creating process loading button with stripes Download Add to gradle root: Download: AndroidX support: Screenshots How to use? Adjust the xml view More examples.: Adjust programmatically ...

    Mastering.Spring.Cloud

    Table of Contents Title Page Copyright and Credits Mastering Spring Cloud Packt Upsell Why subscribe? PacktPub.com Contributors About the author About the reviewer Packt is searching for authors like ...

Global site tag (gtag.js) - Google Analytics