custome UITableview calling methods to store value in cell in iphone - iphone

I am using custom UITableview concept to show data in cell of tableview. My custome uiTableview name is CustomeUITableView.h,CustomeUITableView.m and CustomeUITableView.xib file. This file is consisting following code.
//header file code
#interface CustomTableCellview : UITableViewCell {
UILabel *titleOfPost;
IBOutlet UILabel *userProfileName;
}
#property(nonatomic,retain) IBOutlet UILabel *titleOfPost;
- (void)setTileOfPost:(NSString *)_text;
- (void)setUserName:(NSString *)_text;
#end
// some important part of class file code
- (void)setTileOfPost:(NSString *)_text{
titleOfPost.text = _text;
}
- (void)setUserName:(NSString *)_text{
userProfileName.text = _text;
}
// TableView code where cell is creating and function of cutome UITableview is calling
static NSString *MyIdentifier = #"MyIdentifier";
MyIdentifier = #"tblCellView";
CustomTableCellview *cell = (CustomTableCellview *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if(cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"CustomTableCellview" owner:self options:nil];
cell = tblCell; //IBOutlet CustomTableCellview *tblCell;
}
[cell setTileOfPost:[tableList objectAtIndex:indexPath.row]];
[cell setUserName:[profileUserName objectAtIndex:indexPath.row]];
return cell;
This is calling well and my output is displaying data fine. But here is a bit mistake. I am calling function "setTileOfPost" and "setUserName" in each CELL load. This is making large function calling. I want to fetch all title of text in one call of function. I don't want to use calling function again and again. I stored value in "tableList" and this is extern array defined in main.m file so I can use this array anywhere in application.
How to grab all value in single function call?
Thanks in advance

tableList and profileUserName are of type NSArray or NSMutableArray i suppose. What you can do is in your viewdidLoad method create a copy of these arrays as the data source.
And in cellforrowatindexpath you can directly access these copies.
[cell.title setText:[tableListCopy objectAtIndex:indexPath.row]];
I hope you get the point here. You are having a local copy of the datasource of the tableview.

Related

How do I populate tableview using cell?

to the point, i have custom cells, inside it has 2 label and 1 textfield. both label and textfield got input from user. i also have other view that has uitableview inside it. my question is how do i populate cell in uitableview? please help.
this is my code inside tableviewcontroller.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1; // i want to populate this using 'count' but i dont know how.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier]];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = _customCell;
_customCell = nil;
}
cell.titleLabel.text = [NSString stringWithFormat:#"%#",titleTextString];
cell.timerLabel.text = [NSString stringWithFormat:#"%#",timerString];
cell.statusLabel.text = [NSString stringWithFormat:#"%#",statusString];
return cell;
}
how do i populate my tableview if i push add button after finishing input by user? Please if you dont mind help me with code. i'm beginner and im hard to understand by using opinion.
If I understood your question correctly, you did a custom nib file for your cells that has 2 UILabel in it and one UITextField, and you want to access these objects when populating your table. Here are some steps for this issue:
First, you have to give a tag number for each object in your custom cell. You find this property in the Attribute Inspector in Interface Builder. Say you gave the first label tag 1, the second label 2 and the text field 3.
Second you have to give a. Identifier for this nib file, for example MyCustomCellIdentifier. This identifier will be used later on in the view that has the table so you can link to it.
Third, also in the custom cell nib, you click on the yellow square that says File's Owner and in the Identity Inspector you change the Class to the class name that has the table that will use this custom cell.
Fourth, in the class that you have the table that will use the custom cell, create an outlet of type UITableViewCell. We will link this in the custom nib cell.
Fifth, goto the custom nib cell, click on the cell window, then in the Connections Inspector link New Referencing Outlet to the File's Owner, you will see the outlet that you created in the table class showing here, simply link to it.
Now since the connections are established thing are more easy, in the cellForRowAtIndexPath function (in the class that contains the table for sure), you have to load the custom cell from the nib file as follows:
static NSString *tableIdentifier = #"MyCustomCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TheNibClassNameOfYourCustomCell" owner:self options:nil];
if([nib count] > 0) cell = theNameOfTheOutletYouUsed;
else NSLog(#"Failed to load from nib file.");
}
Ok, your custom cell is loaded in variable cell, now you have to access every object in it from the tags you created:
UILabel *label1 = (UILabel *)[cell viewWithTag:1];
UILabel *label2 = (UILabel *)[cell viewWithTag:2];
UITextField *textField1 = (UITextField *)[cell viewWithTag:3];
Now you can access everything through label1, label2, and textField1 easily like label1.text = #"Hi";
I hope this answers your question.

Iphone UITableViewCell CustomCell

Attempting to implement a "Simple" a CustomCell,
I have a normal tableViewController that renders fine using the normal "default" methods,
but I need to implement a Custom cell with some UILabel's and a UIImage.
So I created the CustomCell.h, CustomCell.m, CustomCell.xib
The .H
#interface CustomCell : UITableViewCell <UITextViewDelegate>
{
IBOutlet UIImageView *image;
IBOutlet UILabel *name;
IBOutlet UILabel *date;
IBOutlet UILabel *comment;
}
#property (retain,nonatomic) IBOutlet UIImageView *image;
#property (retain,nonatomic) IBOutlet UILabel *name;
#property (retain,nonatomic) IBOutlet UILabel *date;
#property (retain,nonatomic) IBOutlet UILabel *comment;
and .M
#implementation CustomCell
#synthesize image;
#synthesize name;
#synthesize date;
#synthesize comment;
#pragma mark -
#pragma mark View lifecycle
- (id) initWithController: (Controller *) ctnlr
{
ControllerPointer = ctnlr;
return(self);
}
- (void) SetImage:(UIImageView*)Image
{
image = Image;
}
- (void) SetName:(NSString*)Name
{
[Name retain];
[name.text release];
name.text = Name;
}
- (void) SetDate:(NSString*)Date
{
[Date retain];
[date.text release];
date.text = Date;
}
- (void) SetComment:(NSString*)Comment
{
[Comment retain];
[comment.text release];
comment.text = Comment;
}
anyway, when I attempt to create these customcells in cellForRowAtIndexPath (as one would expect might be implemented) I am left with only a blank screen. So obviously I am missing something big... When I created the .XIB file with "Interface Builder" I made sure to connect the "Referencing Outlets" to the appropriate labels and images.
So following the implied logic of the way the Xcode framework appears to work,
I followed the same reasoning (for lack of an exact example) No worky...
Anyway, if there are any IPhone geeks that would like to enlighten me...
(yes, there are no "[something release]" calls, I am not even sure if anything needed to be alloc'd. Please tell me there's just a couple calls I am leaving out, it can't be too much more than something simple like this Right...?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil] lastObject];
}
NSUInteger row = [indexPath row];
SnsObject *sObj = [SnsArray objectAtIndex:row];
[cell SetName:[sObj getUserName]];
NSUInteger row = [indexPath row];
SnsObject *sObj = [SnsArray objectAtIndex:row];
cell.name = [[UILabel alloc]init];
cell.name.text = [sObj getUserName];
cell.date = [[UILabel alloc]init];
cell.date.text = [sObj getDateTime];
cell.comment = [[UILabel alloc]init];
cell.comment.text = [sObj getCommentText];
cell.image = [[UIImageView alloc]init];
cell.image.image = [sObj getImageUrl];
return(cell)
}
Thanks in Advance!
There are other issues with the code beyond what mrcrowl mentioned about now needing to "alloc-init" the outlets. In particular, this line:
cell = [[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil] lastObject];
This is not the typical idiom used to load a custom tableview cell from a .xib. First of all, you pass "owner:self", which means you want to hook up the outlet objects in the .xib file with outlet members in your tableviewcontroller object, probably not what you intended.
Second, you're relying on the order of objects returned from loadNibNamed:owner:options:, which while it may work today, may not work tomorrow, or on a new release of iOS.
Instead, the usual idiom is to declare an outlet for the entire tableviewcell in your tableviewcontroller:
(in the .h file):
...
UITableViewCell *tvCell;
...
#property (nonatomic, retain) IBOutlet UITableViewCell *tvCell;
Then in place of your line, you have this:
[[NSBundle mainBundle] loadNibNamed:#"NewsArchiveTitleTvCell" owner:self options:nil];
cell = tvCell;
self.tvCell = nil;
Normally this isn't done with subclassing, notice how I didn't declare the class as CustomCell, but as a vanilla UITableViewCell. So how to you get at those pesky subviews so you can configure them? Using tags is the normal way:
...
#define kMyKewlLabelTag 1
...
UILabel *kewlLabel = (UILabel *) [cell viewWithTag:kMyKewlLabelTag];
kewlLabel.text = [NSString stringWithFormat:#"Hi there from row %d!", indexPath.row];
...
EDIT:
edit: here's a bit more detail, comments are too short to address the "what's going on here?" question. Here's an excerpt from one of my apps that loads the UITableViewCell from a .xib:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MyShoppingCartTvCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"ShoppingCartTvCell" owner:self options:nil];
cell = tvCell;
self.tvCell = nil;
}
...
// (insert code to grab model data for this row)
...
UILabel *nameLabel = (UILabel *) [cell viewWithTag:1];
nameLabel.text = itemNameStr;
UILabel *countLabel = (UILabel *) [cell viewWithTag:2];
countLabel.text = [NSString stringWithFormat:#"%d", itemCount];
UIImageView *iv = (UIImageView *) [cell viewWithTag:3];
...
Here's what's going on here:
There is no custom UITableViewCell subclass, there is only a .xib file named "ShoppingCartTvCell.xib" containing a UITableViewCell, and UI elements placed inside the UITableViewCell. UI elements whose data must change per row are assigned a unique tag (the tag field is in the CMD-1 Attributes Inspector in IB) so that your code can get a handle to those objects to change them (customize labels, images, etc). Make sure you don't use "0" since all elements by default have a 0 tag. Also, make sure the Identifier field of the UITableViewCell in CMD-1 Attributes Inspector is the CellIdentifier string.
The File's Owner of the .xib file is your table view controller where you want to display the cell. More precisely, it can be any class containing a IBOutlet UITableViewCell *tvCell; member. It is an instance of this class that you pass in as owner to loadNibNamed:owner:options:. As long as the value of the linked outlet is nil in the owner, when you call loadNibNamed:owner:options, the outlet of the owner is filled in with the object from the .xib (as long as the connection was made in the .xib in IB). Understanding that is a magic moment in Apple programming that opens whole new vistas to you :).
You must set self.tvCell = nil; to prepare for the next cellForRowAtIndexPath that needs to load from the .xib. I also sometimes set to nil before loadNibNamed:owner:options:, I think that's a bit safer actually.
Here's how you go about loading your UITableViewCells from a .xib:
In xcode, add an IBOutlet UITableViewCell *tvCell; to your UITableViewController class (including property declaration if you like)
In your xcode project, create a New File, User Interface, Empty Xib. Open this .xib in IB
In IB, drag a TableViewCell from the Library into your empty .xib file under First Responder
Click File's Owner, CMD-4 (Identify Inspector), and under Class select the class containing the IBOutlet UITableViewCell *tvCell that you added (probably your UITableViewController subclass, the class where you're manipulating your table).
Control-drag from File's owner to the UITableViewCell, and select the outlet you want to hook up. This is the field that will hold the newly-loaded-from-xib UITableViewCell when you call loadNibNamed:owner:options with an instance of File's Owner as the "owner" parameter.
Add UI elements into the UITableViewCell (make sure they're inside the UITableViewCell hierarchy). Any elements that you want to customize per-row require a unique tag value.
follow the recipe I gave above in cellForRowAtIndexPath
Have a magic moment where you start to understand how .xib files and File's Owner objects really work together, and start creating lots of cool UITableViewCells and other custom view objects in IB because it's really easy and way better than creating them in code (IMNSHO).
When you load a UITableViewCell from a .xib, you shouldn't need to create the controls manually.
For example, this kind of thing is unnecessary:
cell.name = [[UILabel alloc]init];
This will replace the label loaded from your xib with a new label that has a zero frame -- that is, the new label will be located at 0,0 and will have no width or height. Hence, no worky.
Assuming you have the xib hooked up correctly to CustomCell's IBOutlets, they controls you are seeking should already be there.
P.S. Forgive me if I am reading too much into your method name, but I don't think this line will work either, because the .image property expects a UIImage:
cell.image.image = [sObj getImageUrl];
Ok... Thanks all for the good input, but sometimes the simplest answer is not only the most eloquent, it's the best... Here's what I found to work,, keeping it as simple as possible, without changing a thing outside of one function.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCellIdentifier";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for(id oneObject in nib)
{
if([oneObject isKindOfClass:[CustomCell class]])
{
cell = (CustomCell*)oneObject;
}
}
}
NSUInteger row = [indexPath row];
printf("MainMessageBoard.m cellForRowAtIndexPath = [%i]\n",row);
SnsObject *sObj = [SnsArray objectAtIndex:row];
cell.Name.text = [sObj getUserName];
cell.Date.text = [sObj getDateTime];
cell.Comment.text = [sObj getCommentText];
cell.Image.image = [self resizeImage: [self imageFromURLString: [sObj getImageUrl]] scaledToSize:CGSizeMake(32.0f, 32.0f)];
cell.CommentCount.text = [NSString stringWithFormat:#"(%d)", [sObj getCommentCount]];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return(cell);
}

iPhone - "Class" may not respond to "method"

I am building a simple Navigation-based app using tables.
I have a custom "UITableViewCell" to customize the table cell data attached below.
#interface NewsCell : UITableViewCell
{
IBOutlet UILabel *newsTitle;
}
- (void)setNewsLabel:(NSString *)title;
#end
And then in my RootViewController, I set the text of the label "newsTitle" in "cellForRowAtIndexPath" method as follows.
static NSString *MyIdentifier = #"MyIdentifier";
MyIdentifier = #"NewsCell";
NewsCell *cell = (NewsCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if(cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"NewsCell" owner:self options:nil];
cell = newsCell;
}
[cell setNewsLabel:#"hello testing"];
return cell;
When I run this, the app runs fine, but I get "NewsCell may not respond to '-setNewsLabel:'" warning.
Please help! Thank you.
In RootViewController.m, you need to `#import "NewsCell.h".
Or, stick #import "NewsCell.h" in your project's PCH (pre-compiled header) file.
The underlying issue is that the compiler only knows about methods that it has previously seen when parsing the header files (or ones in the PCH).
You're creating the nib, but not assigning it to anything. See this question to create it right.
Where does the variable newsCell come from? Is it really of type NewsCell?

Custom cell just failing

I'm trying to use a custom UITableViewCell, and I've placed it in the same nib file as the UITableView controller. For this, the files are: NTItems.h, NTItems.m and NTItems.xib.
I have defined the cell in the header file:
IBOutlet UITableViewCell *cellview;
and I've correctly applied the property: nonatomic, retain so it's there:
#property (nonatomic, retain) IBOutlet UITableViewCell *cellview;
In the m file - I've synthesized the variable device and am using this to get the custom cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"cellview";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = self.cellview;
}
Product *aProduct = [appDelegate.products objectAtIndex:indexPath.row];
name.text = aProduct.name;
upc.text = [NSString stringWithFormat:#"UPC%#",aProduct.upc];
price.text = aProduct.pid;
return cell;
}
However, when I load the table, I get this horrible mess:
alt text http://dl.dropbox.com/u/1545603/tablecellissue.png
There should be more than 1 cell showing data as well. It appears that only the last data is showing up right now.
You can't reuse a single cell from an outlet like this. Think about it: you're returning the same cell for every call to tableView:cellForRowAtIndexPath:. It's your job to ask the tableView to dequeue a cell if possible, and create a new one each time it isn't.
Instead, store your custom cell in a separate nib and read that nib within your if (cell == nil) { } code when dequeue fails.
The nib file that contains the custom cell should have its File's Owner NSObject and it should contain only the cell's nib (no other objects).
I use this function to load the nib:
- (id)loadObjectFromNibNamed: (NSString *)inName;
{
id objectsInNib = [[NSBundle mainBundle] loadNibNamed: inName
owner: self
options: nil];
NSAssert1( objectsInNib != nil, #"loadNibNamed %# returned nil", inName );
NSAssert2( [objectsInNib count] == 1, #"lodNibNamed %# returned %d items", inName, [objectsInNib count] );
return [objectsInNib objectAtIndex: 0];
}
Then in my tableView:cellForRowAtIndexPath: I have:
if ( cell == nil ) {
cell = [self loadObjectFromNibNamed: nibName];
}
(I use the same nib name as my cell reuse identifier.)
What's happening is that you're only using one cell for the entire table. That means that the last cell drawn is the only visible one. The prior cells essentially don't exist.
You will want to review this document on how to create custom table view cells from a NIB.
There are step by step instructions there.

iPhone table view - problem with indexPath.row

I'm using indexPath.row do determine in which row of my tableview I do something. The title of my cells is containing a number which should be 1 in the first row and 18 in the last row, so I have 18 rows. This works for the first 11 rows, but after that, I have numbers in the title which seem to be generated randomly! Sometimes 16, then 5, then 18, then 12... and so on.
What's the problem with it/why does the indexPath.row variable behave like that?
My cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"myCell" owner:self options:nil];
cell = cell0;
self.cell0 = nil;
}
UILabel *label;
label = (UILabel *)[cell viewWithTag:1];
label.text = [NSString stringWithFormat:#"Cell %d", indexPath.row];
return cell;
}
Any more suggestions on how to solve the problem? I didn't get it working until now...
// Update with more code:
Here is how I declare the cell. It is in an XIB file (template "empty XIB") in which I just put the cell from the library in IB.
#interface myViewController : UITableViewController {
UITableViewCell *cell0;
}
#property (nonatomic, retain) IBOutlet UITableViewCell *cell0;
Then, at the top of the myViewController.m file:
#synthesize cell0;
My cellForRowAtIndexPath method is already posted above. It is equal to the cellForRowAtIndexPath method in the SDK documentation, and in Apple's example, it seems to work.
What are you trying to accomplish with cell0?
cell = cell0;
self.cell0 = nil;
It looks like you're creating a new cell, but somehow deciding to use an old one. The real culprit looks like the code that is loading the cell actually getting assigned anywhere.
Try just this instead:
if (cell == nil) {
cell = [[NSBundle mainBundle] loadNibNamed:#"myCell" owner:self options:nil];
}
Or perhaps:
if (cell == nil)
{
// TODO: try to avoid view controller
UIViewController *vc = [[UIViewController alloc] initWithNibName:#"IndividualContractWithResult" bundle:nil];
cell = (IndividualContractWithResult_Cell *) vc.view;
[vc release];
}
To would be easier to answer if you give the code where you create cells for your table view. It looks that there's a problem with reusing cells - you reuse previously created cells without setting a new value to it.
It sounds like you are not re-using cells but creating new ones when there are cells available. Look at the sample code for dequeueReusableCellWithIdentifier.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MyCell"] autorelease];
}
cell.text = <your code here>;
return cell;
}
It would seem that you're incorrectly accessing a property here:
cell = cell0;
self.cell0 = nil;
Assuming that you have an instance variable named cell0, by setting it to nil, you may be releasing it before you're ready to use it.
The proper way to do this is:
cell = self.cell0;
self.cell0 = nil;
This way, if cell0 is declared as retain, you'll automatically get an autoreleased cell0 back, whereas if you reference cell0 directly (no self.), you'll get an unretained reference, which will disappear when self.cell0 = nil is called.
The advantage of using a nib-based cell here is that you can use outlets, rather than tags, to identify subviews. You've done the heavy lifting already, you might want to just add an outlet and subclass UITableViewCell to get access to the label.
You will need to retain and autorelease cell0, otherwise when you set self.cell0 = nil, then cell0 has no known references.
cell = [[cell0 retain] autorelease];
self.cell0 = nil;
You can also do this:
cell = self.cell0;
self.cell0 = nil;
.. Since any retain properties should implement their getters with the retain/autorelease pattern.