UITableView scrolling boundaries - objective-c

I'm populating data into an array which is then being inserted into a UITableView. However once the screen gets filled, new cells won't show up because they get appended to the bottom. Is there a way to have it auto-scroll to the bottom upon adding an item? Also, the scrolling works but it isn't ideal. For example, to get to the last item, the user has to scroll and hold down that gesture to make the item appear. IE. My UITableView can hold up to 17 items in its view. After 17 the user can then scroll, however they would not be able to select item 18 because they would have to hold down their scroll gesture. In order to select item 18 they'd have to add say another 10 items.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
// Return the number of rows in the section.
// Usually the number of items in your array (the one that holds your list)
return [_items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Where we configure the cell in each row
static NSString *CellIdentifier = #"trap";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell... setting the text of our cell's label
cell.textLabel.text = [_items objectAtIndex:indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"test");
}

If you have to hold your drag gesture to show 18rd item, I think the problem is your tableView's height didn't set properly. Try to set height to your visible frame height.

When the tableView was loaded,you can set contentOffset manually because you can get the tableViewContentSize this time.

You can not show the last item of the table.
The problem most likely is that your tableview’s height is bigger than
you screen size. Or it can be auto layout issue. Try to make your tableview's height smaller.
Is there a way to have it auto-scroll to the bottom upon adding an item?
[self.items addObject:[NSString stringWithFormat:#"Trawl %d", count]];
[self.tableView reloadData];
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.item.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES]
The following is my whole test Controller
#interface DPCalendarTestCreateEventViewController ()<UITableViewDelegate, UITableViewDataSource, DPCalendarTestOptionsCellDelegate>
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, strong) NSMutableArray *items;
#end
#implementation DPCalendarTestCreateEventViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.items = #[#"TEST", #"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST",#"TEST"].mutableCopy;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneButtonSelected)];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
self.tableView.dataSource = self;
self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.tableView];
}
- (void) doneButtonSelected{
[self.items addObject:[NSString stringWithFormat:#"Trawl %d", self.items.count]];
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.items.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Where we configure the cell in each row
static NSString *CellIdentifier = #"trap";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell... setting the text of our cell's label
cell.textLabel.text = [_items objectAtIndex:indexPath.row];
return cell;
}
#end

Related

How to get a custom UITableViewCell class created in IB to load into a UITableView?

I am new to this so please bear with me:
I have a .xib in IB containing a UIScrollView that has a UITableView embedded in it. I would like to load custom UITableViewCells into the UITableView. I have four/five custom cells created in IB but cannot get the first to load correctly.
Here are relevant screenshots from IB:
I have set the class for the custom UITableViewCell created in IB to the UITableView class I created called "itemCell". Additionally, I have connected the three text fields outlets and delegates to "itemCell".
Here is itemCell.h:
#import <UIKit/UIKit.h>
#interface itemCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UITextField *quantityTextField;
#property (weak, nonatomic) IBOutlet UITextField *itemTextField;
#property (weak, nonatomic) IBOutlet UITextField *priceTextField;
#end
Here is itemCell.m:
#import "itemCell.h"
#implementation itemCell
#synthesize quantityTextField,itemTextField,priceTextField;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
In filecontroller.m, which is the rootcontroller .xib's implementation file I create a new cell based on the user pressing a button (add it to an array) and then reload the tableview. I am getting no errors but I am getting a normal cell loaded in rather than what I have created in IB. Here is rootcontroller.m. Any help is appreciated.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
scrollView =(UIScrollView *)self.view;
items = [[NSMutableArray alloc] init];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
return [items objectAtIndex:[indexPath row]];
}
- (UITableViewCell *)initiateNewCell{
itemCell *cell = [[itemCell alloc] init];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
return cell;
}
- (IBAction)addItem:(id)sender {
//creates the new cell to be added
[items addObject:[self initiateNewCell]];
[self.tableView reloadData];
As of iOS 5 you can now load a UITableViewCell from a nib for cell reuse with the following function.
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
First make sure you create an IB file that contains only the UITableViewCell
Under Identify inspector: Set the class of the UITableViewCell to "itemCell"
Under attributes inspector: Set the identifier of the UITableViewCell to "itemCellIdentifier"
In viewDidLoad: place the following code, and replace itemCellNibName with the name of the nib that contains the UITableViewCell.
NSString *myIdentifier = #"itemCellIdentifier";
[self.tableView registerNib:[UINib nibWithNibName:#"itemCellNibName" bundle:nil] forCellReuseIdentifier:myIdentifier];
In cellForRowAtIndexPath: place the following code, you can now access your IBOutlet properties you set on the itemCell, and connected in the nib.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *myIdentifier = #"itemCellIdentifier";
itemCell *cell = (itemCell *)[tableView dequeueReusableCellWithIdentifier:myIdentifier];
cell.textLabel.text = [NSString stringWithFormat:#"Test Row:%i!",indexPath.row];
return cell;
}
Also: You do not want to include the UITableView inside a UIScrollView, a UIScrollView is already built into the UITableView, which allows for proper cell queing.
Also: I suggest you just get the bare bones of this going first, before you start pulling data from an array.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
Also: As someone else had mentioned, the array contains the data that will populate the UITableViewCells, not the actual cells themselves.
In your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//This identifier string needs to be set in cell of the TableViewController in the storyboard
static NSString *CellIdentifier = #"Cell";
// Resuse the cell
SomeCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// If there are no cell to be reused we create a new one
if(cell == nil) {
cell = [SomeCustomCell new];
}
// Configure the cell...
NSString *someString = [yourArrayWithStringsOrWhatEver objectAtIndex:indexPath.row];
// Setting the some property of your custom cell
[cell.yourSpecificCellProperty someString];
[cell.yourOtherSpecificCellProperty setText:#"What Ever your want!"];
}
Your cell's properties could be whatever your have connected to your custom cell in interface builder.
Hope it helps!
Well there are a few things that aren't right:
The class name begins with upper case letter itemCell -> ItemCell
You should reuse the cell. The way you want to do this, you will create a separate cell for each index path.
the items array should only contain the data source of your table, not your cells
instead of calling reload data, you can add just one row to the table, and it can be animated too
Try something like:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
scrollView =(UIScrollView *)self.view;
items = [[NSMutableArray alloc] init];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[NSBundle mainBundle] loadNibNamed:#"itemCell" owner:self options:nil].lastObject;
cell.reuseIdentifier = CellIdentifier;
}
// Do any additional setup to the cell
return cell;
}
- (IBAction)addItem:(id)sender {
[items addObject:[NSNumber numberWithInt:items.count]]; // Here comes the data source
[self.tableView insertRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:items.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
}
PS: I wrote it without an IDE so there might be some errors

How to directly edit a row in a UITableView, without entering in Editing Mode

In a UITableView, I would like to be able to edit the cell.textLabel.text property of the row, when such row is touched.
In other terms, I would like to be able to edit the row directly touching it, instead of entering into edit mode.
How can I implement this?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CMTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
int tagsCount = [[currentComic Tags] count];
[[cell textField] setTag:[indexPath row]];
[[cell textField] setText:[tagsDisplayName objectAtIndex:[indexPath row]]];
return cell;
}
And this is the subclass CMTableViewCell:
...
-(void)viewDidLoad
{
textField = [[UITextField alloc] init];
[textField setFrame:CGRectMake(5,5,50,400)];
[self addSubview:textField];
}
Add UITextField without borders as subview. Before adding it to subview - set Tag nubmer to UITextField from indexPath.row at tableview cellForRowAtIndexPath method. When user entered data - save it with UITextFieldDelegate methods when "Return" button was pressed. Unfortunately I can't give you code, because right now I'm on Windows. Home this will help
UPDATE: Tag number needed to change data in your DataSource. When you pressed "Return" button in your UITextField, you can save changed by getting UITableViewCell by this tag number from UITextField.
It's simple:
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.text = #"...";
}
UPDATE
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITextField *textField = [[UITextField alloc] init];
[textField setTag:[indexPath row]];
[tagsTableView addSubview:textField];
FreeAndNil(textField);
}

How to keep selection of untouched cells intact?

I have a tableView where I select cells and add the data in an array, I also have the option of swiping and then deleting a particular cell which eventually deletes the data from the array.
The problem is that once I delete a row, I lose all my selection state after I reload the table,
For that I checked again with the selection array and reselected all these cells,
BUT I am stuck at one place, Much before I actually delete a cell and reload the tableView, as soon as I swipe over a cell, selection state of all other cells also go away.
NOTE: I have two arrays, one with list of itmes to be displayed in the tableView and one with the selected items.
Here is some code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.contactList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
[cell.textLabel setTextColor:[UIColor colorWithRed:103.0/255.0 green:103.0/255.0 blue:103.0/255.0 alpha:1.0]];
[cell.textLabel setFont:[UIFont fontWithName:#"ITCAvantGardeStd-Bk" size:14.0]];
if (![[[self.contactList objectAtIndex:indexPath.row] objectForKey:#"nickName"] isEqualToString:#""])
cell.textLabel.text = [NSString stringWithFormat:#"%#",[[self.contactList objectAtIndex:indexPath.row] objectForKey:#"nickName"]];
else
cell.textLabel.text = [NSString stringWithFormat:#"%# %#",[[self.contactList objectAtIndex:indexPath.row] objectForKey:#"firstName"],[[self.contactList objectAtIndex:indexPath.row] objectForKey:#"lastName"]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Selected cell index==>%d\n",indexPath.row);
//NSString *emailID = [NSString stringWithFormat:#"%#",[[self.contactList objectAtIndex:indexPath.row] objectForKey:#"email_key"]];
NSLog(#"emailID==>%#\n",[self.contactList objectAtIndex:indexPath.row]);
[self.emailShareList addObject:[self.contactList objectAtIndex:indexPath.row]];
//[self.emailShareList insertObject:emailID atIndex:indexPath.row];
NSLog(#"Array value==>%#\n",self.emailShareList);
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"deSelected cell index==>%d\n",indexPath.row);
NSString *emailID = [NSString stringWithFormat:#"%#",[[self.contactList objectAtIndex:indexPath.row] objectForKey:#"email_key"]];
NSLog(#"emailID==>%#\n",emailID);
[self.emailShareList removeObject:[self.contactList objectAtIndex:indexPath.row]];
NSLog(#"deSelect row Array value==>%#\n",self.emailShareList);
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
if(indexPath.row != 0)
{
NSString *contactID = [[self.contactList objectAtIndex:indexPath.row] objectForKey:#"contactId"];
NSLog(#"content on delete row==>%#\n",contactID);
[self.contactList removeObjectAtIndex:indexPath.row];
[self deleteContactToServer:contactID];
}
}
[contactTableView reloadData];
for (int i = 0; i < [self.emailShareList count]; i++)
{
for (int j = 0; j < [self.contactList count]; j++)
{
if([[[self.contactList objectAtIndex:j] valueForKey:#"email"] isEqualToString: [[self.emailShareList objectAtIndex:i] valueForKey:#"email"]])
{
NSIndexPath *path1 = [NSIndexPath indexPathForRow:j inSection:0];
[contactTableView selectRowAtIndexPath:path1 animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}
}
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCellEditingStyle style = UITableViewCellEditingStyleNone;
if(indexPath.row != 0)
style = UITableViewCellEditingStyleDelete;
return style;
}
When you delete an item, you don't necessary have to reload the entire tableview. You could use the – deleteRowsAtIndexPaths:withRowAnimation: method to just remove the cell in question (along with an according model update). This will probably retain your selection.
To keep your selections when entering editing mode (swipe for delete is a special case of editing mode as well) you nee to do two things:
First, enable allowsSelectionDuringEditing on your tableView:
self.tableView.allowsSelectionDuringEditing = YES;
Second, create a UITableView subclass and override setEditing:animated: like this:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
NSArray *indexPaths = self.indexPathsForSelectedRows;
[super setEditing:editing animated:animated];
for (NSIndexPath *ip in indexPaths) {
[self selectRowAtIndexPath:ip animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}
Personally, I would rather use some sort of custom selection mechanism, when selections are important from a model point of view. I would create a custom cell subclass, add a selection property to it let it change the cell styling accordingly. The build-in features that affect regular table view selections won't cause problems with such an approach.
Here is an additional method of preserving table selections in and out of edit mode without having to subclass UITableView. Add the following to your UITableViewControllerView.
Within viewDidLoad add:
self.tableView.allowsSelectionDuringEditing = YES;
Then override setEditing:animated:
- (void)setEditing:(BOOL)editing animated:(BOOL)animate
{
NSArray *selectedIndexPaths = [self.tableView indexPathsForSelectedRows];
[super setEditing:editing animated:animate];
for (NSIndexPath *selectedIndexPath in selectedIndexPaths) {
[self.tableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}

Looping through subview of a custom cell in didSelectRowAtIndexPath to get UITextField text

i know im asking a very common question. but after going through a lots of similar questions and articles im not able understand
How can i access UITextfield inside UITableViewCell inside didSelectRowAtIndexPath delegate method.
im posting my code below. i may b not going with expected way although..
i want to make textfield (of selected row) [becomeFirstResponder] in didSelectRowAtIndexPath
so that i can display uiPicker below to this textfield. Please help me out with this.
- (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];
if(self.isTableForHospital)
{
UIView *myview=[self createRowViewForHospitalTable:[customArray objectAtIndex:indexPath.row]];
myview.tag=indexPath.row;
[cell addSubview:myview];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
else
{
cell.textLabel.text=[customArray objectAtIndex:indexPath.row];
}
}
return cell;
}
-(UIView *)createRowViewForHospitalTable:(NSString *)rowText
{
UIView *hospital_row_view=[[UIView alloc]init];
UILabel *lblRowText=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 50)];
lblRowText.text=rowText;
txtDepartment=[[UITextField alloc]initWithFrame:CGRectMake(310, 0, 185, 30)];
//...rest styling for textfield goes here..
txtRole=[[UITextField alloc]initWithFrame:CGRectMake(495, 0, 185, 30)];
[hospital_row_view addSubview:lblRowText];
[hospital_row_view addSubview:txtDepartment];
[hospital_row_view addSubview:txtRole];
return hospital_row_view;
}
- (void)textFieldDidEndEditing:(UITextField *)textField { }
- (void)textFieldFinished:(id)sender{
NSString *value=#"sa";
[sender resignFirstResponder];
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cellSelected = [tableView cellForRowAtIndexPath: indexPath];
UIView *myview=[cellSelected.contentView viewWithTag:indexPath.row];
for(UIView *item in [myview subviews])
{
if([item isKindOfClass:[UITextField class]])
{
[item becomeFirstResponder];
}
}
}
In terms of iterating through the cell subviews and getting the UITextField, I think I have your answer.
I found this on another thread here, and modified it to be more generic:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITextField* textField = [[UITextField alloc] init];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
UIView* subview = [[cell.contentView subviews] lastObject]; // Make sure your UITextField really *is* the last object you added.
if ([subview isKindOfClass:[UITextField class]]) {
textField = (UITextField*)subview;
}
[textField becomeFirstResponder];
}
...where "textField" is the placeholder for your actual text field object.
Hope this helps!
I don't think you need to alloc init the textfield, for it will ultimately be pointing to the cell's textfield (if any).
I believe you are allocating it unnecessarily.

Howto fill UITableView with sections and rows dynamically?

I have some problems with UITableView and sections/rows.
Iam parsing the section names, all row names and row count per section from a xml.
I have 3 NSMutableArrays:
nameArray (with all row names)
sectionArray (all section names)
secCountArray (row count per section)
For the cellForRowAtindexPath to work, do I have to return the rows for the displayed section?
The next step I would do is to build an 2d Array with sections and all rows for each section.
Does anyone knows any better solution?
Here comes the code:
// Customize the appearance of table view cells.
- (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] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set up the cell
int xmlEntryIndex = [indexPath indexAtPosition: [indexPath length] -1];
//???
cell.textLabel.text = [[theParser.nameArray objectAtIndex: 1]valueForKey:#"name"];
return cell;
}
Thanks!
You could have one _section array and one _row array for the whole tableview.
like your view controller.h file declare array
NSMutableArray *arrSection, *arrRow;
then your view controller.m file paste below code..
- (void)viewDidLoad
{
[super viewDidLoad];
arrSection = [[NSMutableArray alloc] initWithObjects:#"section1", #"section2", #"section3", #"section4", nil];
arrRow = [[NSMutableArray alloc] init];
[arrSection enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSMutableArray *tempSection = [[NSMutableArray alloc] init];
[arrSection enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[tempSection addObject:[NSString stringWithFormat:#"row%d", idx]];
}];
[arrRow addObject:tempSection];
}];
NSLog(#"arrRow:%#", arrRow);
}
#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrSection count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [arrSection objectAtIndex:section];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[arrRow objectAtIndex:section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:nil];
if(!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
cell.textLabel.text = [[arrRow objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
return cell;
}
This method does not involve defining and creating your own custom view. In iOS 6 and up, you can easily change the background color and the text color by defining the
- (void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
delegate method.
For example:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor blackColor];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// header.contentView.backgroundColor = [UIColor blackColor];
}
you can see display dynamic section and row
May be helpful for you..
You could have one array for the whole table view. The array contains arrays for every section. Then the cellForRowAtIndexPath could look like:
- (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] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
[[cell textLabel] setText: [[[myArray objectAtIndex: indexPath.section] objectAtIndex: indexPath.row]];
return cell;
}
I hope this help you in your problem.
Edit: With the modern Objective-C and ARC I would write this as
- (void)viewDidLoad {
....
[self.tableView registerClass:[MyCellClass class] forCellReuseIdentifier:kMyCellIdentifier];
}
...
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
MyCellClass *cell = [tableView dequeueReusableCellWithIdentifier:kMyCellIdentifier forIndexPath:indexPath];
cell.textLabel.text = myArray[indexPath.section][indexPath.row];
return cell;
}