How do I populate tableview using cell? - iphone

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.

Related

UITableView CustomCell crash on Button Click

This is very common question at SO though I have google and cross check my code few times but I am not able to figure out the crash
*** -[MyCustomCell performSelector:withObject:withObject:]: message sent to deallocated instance 0x96f6980
I have a CustomCell named MyCustomCell with XIB where I have 3 buttons for Facebook,Twitter,LinkedIn. I gave them all IBAction in CustomCell class.
When I click on any of them I get this kind of crash.
I am using ARC.
In my ViewController class I have cellForRowAtIndexPath
{
static NSString *CellIdentifier = #"MyCustomCell";
MyCustomCell *cell = (MyCustomCell*)[myTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
cell = (MyCustomCell *)[nib objectAtIndex:1];
}
return cell;
}
MyCustomCell.m
- (IBAction)facebookPressed:(BaseButton *)sender {
}
- (IBAction)twitterPressed:(BaseButton *)sender {
}
- (IBAction)linkedInPressed:(BaseButton *)sender {
}
I made this mistake just today! :) all you gotta do is replace the 2 lines
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"NameOfCustomCellNibFile" owner:self options:nil];
cell = [nib objectAtIndex:1];
You have to load the loadNibNamed: with the .xib file's name. I also thought it was with the identifier, but that is regarding the name that is referenced into the cell instead of the nib for the cell.
Hope this helps!
you can also code for Custom cell like this way. At nib of custom cell drag one UIButton and set it's tag in Xib. then use bellow Method:-
UIButton *btnMulSelected;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier =[NSString stringWithFormat:#"%d_%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle]loadNibNamed:#"cell_custome_iphones" owner:self options:nil];
cell = self.tblCell;
self.tblCell = nil;
btnMulSelected =(UIButton*)[cell.contentView viewWithTag:2];
[btnMulSelected addTarget:self action:#selector(MyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
Do not connect IBAction from Nib. just connect Custom-cell IBOutlate or put Unique UIButton tag from nib.
You've to keep the class name of cell and the XIB names same.
Keep the owner nil generally.
Also, if there is only 1 view ( i.e. 1 UITableViewCell in your case ), then this view is available at index 0 instead of index 1.
Inside the XIB file, make sure you link the button to your view itself, i.e. to IBOutlet or IBAction.
The linked buttons must be already added to your view, not floating outside in XIB. Otherwise they will instantiate and come at other indices of the loaded array. If you don't want a certain button for some time, then just keep it hidden.
So the code can be as below:
NSArray *views = [[NSBundle mainBundle] loadNibNamed:#"MyCustomCell" owner: nil options:nil];
MyCustomCell *cell = (MyCustomCell*)[views objectAtIndex:0];
Further make sure you do the following for creating XIB
Ok, then here goes the other portion simple process:
Create a MyCustomCell class derived from UITableViewCell class.
Create a separate .xib file with same name as MyCustomCell.xib.
Open .xib and delete the existing view in it. drag and drop a new
UITableViewCell from the objects of editor.
See the image to change the class name of the UITableViewCell in XIB to your class name.
Now the objectAtIndex 0 will return MyCustomCell.
Add all your buttons and other views in this UITableViewCell of your XIB.

How to initialize a custom tableview cell

I am using storyboard and custom cells. I am trying to search. It works all fine and loads the custom cell when the tableviewcontroller loads , as soon as i enter a search character, the cell returned is UITableViewCellStyleDefault and i can only set the label, i am not sure why it is not picking the custom cell. Can someone please help.
sorry its a repeat of this but i could not figure out how that worked.
i am using this code.
static NSString *CellIdentifier = #"memberCell";
MemberCell *cell = (MemberCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *item = self.searchList[indexPath.row];
if (cell == nil) {
cell = [[MemberCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.memberFullName.text = [item[#"full_name"] uppercaseString] ;
cell.memberPosition.text = [item[#"title"] length] < 1 ? [NSString stringWithFormat:#"%#", item[#"districts"]] : [NSString stringWithFormat:#"%#, %#", item[#"title"], item[#"districts"]];
cell.memberRoom.text = [NSString stringWithFormat:#"Rm %#", item[#"room_number"] ];
[cell.memberImage setImageWithURL:[NSURL URLWithString:item[#"image_thumb"]]
placeholderImage:[UIImage imageNamed:#"placeholder"]];
Deepak
You said "I am trying to search" - do you mean that you added a UISearchDisplayController and you are trying to get your custom cell to appear in that results table view? If so, you have 2 options:
In the tableView:cellForRowAtIndexPath: method you need to dequeue the custom cell from your main table view and NOT the search results table view. When you define a cell in tableview that is in a storyboard, the storyboard only registers it with that tableview, so it isn't dequeueable from any other tableview (I confirmed this with the apple engineer responsible for storyboards at WWDC '13). So, the code would look like this instead:
MemberCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Move your custom cell definition into a standalone xib file (create an empty XIB, drag a UITableViewCell from the objects list and configure it as desired). Define a custom cell class and configure that as the cell class in the xib, and then you can manually register that cell type with both table views using registerNib:forCellReuseIdentifier:

UITableViewController cell design issue

I have a UITableViewController with an attached xib file. Inside the xib file i have a TableViewCell object with a view inside it along with labels on the view. Below is an image of what my result should be:
pic1 http://casperslynge.dk/2.png
And below is how my tableview is looking atm.
pic2 http://casperslynge.dk/iphone1.png
My issue is that I can't get the table view cell to fill the entire window. Have tried everything inside the interface builder. Nothing to do with the origin or the width/height. Below is how I instantiate my cell with the xib file and fill my labels with data.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * CompanyListCellIdentifier =
#"CompanyList";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CompanyListCellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CompanySubscriptionView" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
NSUInteger row = [indexPath row];
CompanyModel *company = [list objectAtIndex:row];
name.text = company.name;
network.text = company.networks;
NSString* subscriptionCountString = [NSString stringWithFormat:#"%d", company.subscriptions.count];
subscriptionCount.text = subscriptionCountString;
fromPrice.text = company.fromPrice;
NSString* trustScoreString = [NSString stringWithFormat:#"%d", company.trustScore];
trustScore.text = trustScoreString;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
The weird thing is that in the next view when one of the cell's are pressed, I have no issue making the view fill the entire width and height, and it is created in exactly the same way (see picture below). Is it something in the xib file that I am doing wrong or in the code?
pic3 http://casperslynge.dk/iphone2.png
Can anybody help?
As I see from screenshots you are trying to use table view with grouped style while you definitely need a plain one (at least for first view).

Setting a UITableViewCell subview tag property

I have a UITableView, cells of which are customised in a NIB file so I can have a UILabel and UITextField.
Therefore my cellForRowAtIndexPath looks like this:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SectionCustomCell *cell = (SectionCustomCell *)[tableView
dequeueReusableCellWithIdentifier: #"Section"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SectionCustomCell"
owner:self
options:nil];
cell = [nib objectAtIndex:0];
// Set the label value
[[cell inputLabel] setText:#"something"];
// Set the textfield tag property
}
Therefore for a given section/row I am going to assign some text to the UILabel, defined as inputLabel, and have a UITextField, called inputTextField get some text from the user.
My plan is to set the tag property of the UITextField so I can determine which field I am getting in the delegate textFieldDidEndEditing.
Now my problem, if I put this code:
UITextField *textField = nil;
for (UIView *oneView in cell.contentView.subviews)
{
if ([oneView isMemberOfClass:[UITextField class]])
textField = (UITextField *)oneView;
}
textField.tag = [indexPath row];
the tag property is set correctly. (I know this from a NSLog statement). However if I do the following it is not set correctly. It is always 1 as defined in IB.
cell.inputTextField.tag = [indexPath row];
but to me this should work. I am doing the same principle with the setting the labels text. Can someone help me to understand why it doesn't work?
I'm new to iOS so go gentle :-)
Thanks
Mike
Make sure you have connected the textfield and the IBOutlet in IB.
If that doesnt work try putting this in the code:
NSLog(#"%i", cell.inputTextField == nil);
If it prints 1 to the console then it means the inputTextField is nil so somewhere between the nib file, your custom class and the tableview datasource the connection is getting lost. But as I first said this is most likely the textfield is not connected properly in IB.

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.