Managing UITableViewCell selected states - ios

I have UITableViewController with a static table view and 2 sections. The first section has two cells, with a layout Table View Cell > Content View > Text Field.
The second section of table view cells has a layout that is Table View Cell > Content View > Label - and the cells expand when they're selected by using beginUpdates and endUpdates and reporting cell heights via tableView:heightForRowAtIndexPath:.
Right now, when I touch one of the first sections' cells, the keyboard comes up and the cursor is placed in the text field, but the cell is not selected - which means that if I had previously selected one of the cells in the second section, it would remain selected (and therefore expanded).
Also, if I have selected a cell in the first section with the text field given first responder, then I select a cell in the second section, the cell expands, but the first cell does not resign first responder and dismiss the keyboard.
Did I layout my table view incorrectly such that the cell selected states are not managed automatically and if not: what is the proper way to manage the selected states of the UITableViewCells?

I dont know how you have written the code. But from above information I have created one sample application. The code is as below and it is working as you want.
I have considered the table with 2 section.
First section has the textfield on Cell.
Second section has the UIlabel on the cell.
txtFieldCopy is of type UITextField declared in .h of class.
Please check the way I have assigned the Tag to the view as we need it to get the indexpath.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCellStyle style =UITableViewCellStyleSubtitle;
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
int iTag=[indexPath row]+1;
txtFieldCopy=nil;
if(indexPath.section==1)
{
UILabel *lblFirst=nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:MyIdentifier];
lblFirst = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 100,
40)] ;
lblFirst.tag=iTag;
[cell.contentView addSubview:lblFirst];
lblFirst=nil;
}
lblFirst = (UILabel *)[cell.contentView viewWithTag:iTag];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
lblFirst.text =#"Label 1";
}
else
{
UITextField *txtFirst=nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:MyIdentifier];
txtFirst = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, 50,
40)] ;
txtFirst.tag=iTag;
txtFirst.delegate=(id)self;
[cell.contentView addSubview:txtFirst];
txtFirst=nil;
}
txtFirst = (UITextField *)[cell.contentView viewWithTag:iTag];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
txtFirst.text =#"text 1";
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(txtFieldCopy)
{
[txtFieldCopy resignFirstResponder];
txtFieldCopy=nil;
}
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"%d",textField.tag);
NSIndexPath *iRowId =[NSIndexPath indexPathForRow:(textField.tag-1) inSection:0];
[tblSample selectRowAtIndexPath:iRowId animated:NO scrollPosition:UITableViewScrollPositionMiddle];
txtFieldCopy=textField;
}
Make sure if suppose in between you are reloading the table view then txtFieldCopy=nil; in the cellForRowAtIndexPath get called and set to null. so you can ignore this line. But before please check whether you are calling it again and again.
Let me know if it worked for you or not. I am sure it definitely work for you

Related

Cell and TextField not showing serialwise in UITableView

I am using UITextField, and every row have a CellLable and TextField. Lable and TextField data comes from array. While running the app, all data are comes fine but when scrolling the Tableview, Last 2-3 Rows unorganized.
NSMutableArray
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ArrFieldData= [NSMutableArray arrayWithObjects:#"Fist Name", #"Last Name",#"User Name", #"Password",#"Confirm Password", #"Gender",#"DOB", #"Profile Pic",#"Deparment", #"Joining Date",#"Education", #"Role", nil];
Now cellForRowAtIndexPath Function
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
UITextField *txtField ;
if (cell ==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
txtField = [[UITextField alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/3 + 40, 2, [UIScreen mainScreen].bounds.size.width/2, cell.layer.frame.size.height -5)];
[self setUpCell:cell withIndexPath:indexPath withTextField:txtField];
}
[self UpdateCell:cell withIndexPath:indexPath withTextField:txtField];
return cell;
}
SetUp Cell Function
-(void)setUpCell:(UITableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath withTextField: (UITextField *)txtField {
cell.textLabel.text = [ArrFieldData objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:12.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
txtField.tag = indexPath.row+1;
txtField.layer.borderColor = [UIColor grayColor].CGColor;
txtField.delegate = self;
txtField.layer.borderWidth = 1.0f;
txtField.layer.cornerRadius = 4.0f;
txtField.placeholder = cell.textLabel.text;
txtField.font = [UIFont systemFontOfSize:12.0];
[cell.contentView addSubview: txtField];
}
Update Cell Function
-(void)UpdateCell:(UITableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath withTextField: (UITextField *)txtField {
[self setUpCell:cell withIndexPath:indexPath withTextField:txtField];
}
First time Running the application, It is showing all cell and textfield data are Serialize. but when scroll some cell and TextField are not serialize as per Array Value. I am attaching the Simulator Screenshot.
First Screenshot for First time running, and second for when i scroll the Tableview. See the last 4-5 cell and Textfield Placeholder text. They are un-organized. I want it shouldn't change.
As you are using reusable cells, like
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
UITextField *txtField ;
if (cell ==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
txtField = [[UITextField alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/3 + 40, 2, [UIScreen mainScreen].bounds.size.width/2, cell.layer.frame.size.height -5)];
[self setUpCell:cell withIndexPath:indexPath withTextField:txtField];
}
[self UpdateCell:cell withIndexPath:indexPath withTextField:txtField];
return cell;
}
UITableView uses the concept of reusable cell to achieve maximum performance by reducing the memory consumption, and to exploit this feature of reusing cells you can use the above UITableView's API's to achieve that.
But before using any feature it's very important to understand the working and the usage of any feature.
In your above implementation of tableView: cellForRowAtIndexPath: method, you have used the concept of cell reusability.
If the cells doesn't exist and are created for the first time, than they are allocated(every subview is created and added on the content view of the cell), customized and initialized with the data from the data source of the respective index path.
But in case the cells are reused(as they were already created for any other index path), there subviews exist with the data already filled for the previous index path for which it was created.
Now there are two things we can do to use already created cell for the current index path,
1) if the cells contain subview with data then remove the subviews and recreate the new ones, customize and populate them with the data.
2) rather than releasing the previous subviews and creating new ones, refill the data for the data model of the corresponding index path.
In your case, if the cell is being created for any index path, than the text filed for it is also created and if it's reused than the new text field is not created and it's being reused from the previously created cell thus the issue of the placeholder text not matching with the left text.
So, in order to solve your problem I think you should either create the textfield when the cell is created and if the cells are reused than refill the data in the text filed from the data source of the corresponding index path.
Your problem is due to a feature of UITableView. When you scroll a UITableView the indexPath is updated so you are not getting the index values you are expecting from the tableView.
Instead of adding a UITextField programmatically. Create a Custom UITableViewCell and from the method cellForRowAtIndexPath: update the placeHolder of your UITextField. The tableView will take care of scrolling for you.
Use this code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
UITextField *txtField ;
if (cell ==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
cell.textField.placeholder= cell.textLabel.text;
}
cell.textField.placeholder= cell.textLabel.text;
return cell;
}

Tableview button click need pickerview in ios

Creating the UIpickerview in tableview button click. When click the each button first time the picker want to show . if i click the same button in another time picker want to hide and get the picker value. here i put my code only the last cell index done the process the first cell index is not working? how can i fix this issues help me!!! here screen!.
create the picker in global like
UIPickerView *myPickerView;` and acess in tableview
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_arr_tags count]; /// in tag array number of button count
}
-(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:nil];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
/// create a button
UIImage *ButtonImagecmt = [UIImage imageNamed:#"orangeButton#2x.png"];
UIButton *myButtoncmt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButtoncmt.frame = CGRectMake(10,50,90,35);
[myButtoncmt setBackgroundImage:ButtonImagecmt forState:UIControlStateNormal];
[myButtoncmt addTarget:self action:#selector(picker_select:)forControlEvents:UIControlEventTouchDown];
[cell addSubview:myButtoncmt];
flg=1; /// first time picker want to hide so flag set 1.
myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(120, 0, 160, 180)];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
myPickerView.hidden=true;
[cell addSubview:myPickerView];
}
return cell;
}
- (IBAction)picker_select:(id)search
{
if (flg==1)
{
/// first time button clickt picker want to display
myPickerView.hidden=false;
flg=0;
}
else
{
/// secound time button click picker want to hide
myPickerView.hidden=true;
flg=1;
}
}
This code only working in last cell. want to work in all the cell in table view
First let me explain your error after that I will suggest you other way.
You are declaring UIPickerView *myPickerView; in out side of following method
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
But you are initializing myPickerView inside of following method
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
and again you are trying to access myPickerView outside of the following method
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
simply the object myPickerView represents last cell pickerview. so what ever button you tapped in table view, myPickerView always represents last cell pickerview. As per reusability concept, you can't see this picker until you are loading last cell on screen.
so what I am suggesting you to work with your code
set index row as tag to your button like bellow in cellForRowAtIndexPath method
myButtoncmt.tag = indexpath.row;
now in the same way set tag to your pickerview also(I am not recommended this but I am trying to resolve issue with your code ) like bellow
myPickerView.tag = [_arr_tags count]+indexpath.row;
Now in - (IBAction)picker_select:(id)search access that using following code
UIButton *tempBtn =(UIButton *) search;
UITableViewCell *cell= [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:tempBtn.tag inSection:0]]
UIPickerView *pickerView = [cell viewWithTag:[_arr_tags count]+tempBtn.tag];
pickerView.hidden = !pickerView.isHidden;
Now you can see all pickers. try and let me know your result

ios MasterDetail app: UITextField in tableview not work

I have a master detail app in ios, with SDK 7.0, Xcode 5, using ARC.
master has many items, detail has a table view. When I click on an item, the contents of tableview will change. This works well until I put a UITextField in each cell, because I want to edit the contents in the table.
The problem is: when I click on a new item, the old contents don't disappear,so the contents of a cell is a superposition of the new UITextField's text and the old UITextField's text.
The first normal tableview like this:
After I click on an new item, the tableview will like this:
The snippet of codes of master is:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
LHBPoetry *poetry = poetryArray[indexPath.row];
self.detailViewController.poetryId = poetry.poetryId;
}
I have tried a lot of things in the above method, for example, I make all instances of the detail view controller to be nil; table view's data array removeAllObejects; table view reloadData; It can't fix the problem.
The snippet of detail is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"detailCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
UITextField *textField = textField = [[UITextField alloc] initWithFrame:
CGRectMake(90, 12, 200, 25)];
textField.tag = indexPath.row;
textField.text =_sentenceArray[indexPath.row];
textField.clearsOnBeginEditing = NO;
textField.delegate = self;
textField.returnKeyType = UIReturnKeyDone;
[textField addTarget:self
action:#selector(textFieldDone:)
forControlEvents:UIControlEventEditingDidEnd];
[cell.contentView addSubview:textField];
textField.text = _sentenceArray[indexPath.row];
return cell;
}
I draw this tableview in Main.storyborad, It has a prototype cell with an identifier.
Any help will be appreciated.
k there is something i want to tell, wy because u are keep on adding the textfields for reused cells, there is not one textfield in the cell ..:) there are more then one text field's, because of that u are getting overlapped with one other, i think u are using default "master- detail" application, and modifying it..:)
oky for that u need to modify like below
in master controller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(2, 3, 300, 30)];
[textField addTarget:self action:#selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEnd]; //hear u are adding once initially
textField.tag = 100;
[cell addSubview:textField];
}
NSString *object = _objects[indexPath.row];//_objects is mutable array holding the sentences or names
UITextField *textField = (UITextField *)[cell viewWithTag:100];//after that u are reusing the textfields
textField.text = object;
textField.tag = indexPath.row;
return cell;
}
now you are creating the cell thats wy u dont want the prototype cell remove it from story board
in the above u removed the custom cell becz u are creating the cell in the code it self
now in the method
- (void) textFieldDone:(UITextField *)inTextFIeld
{
int index = inTextFIeld.tag;
[_objects replaceObjectAtIndex:index withObject:[inTextFIeld text]];
[self.masterTableVIew reloadData];//made connection to ur tableview
}

Expanding and Collapsing table view cells in ios

I have a table view of custom cells and some buttons in each cell.Clicking on any of the button inside the cell will reveal another custom view below that cell.Next click on the same button will collapse the view and need this same for all cells.I tried with insertrow method on the button click but in vain.How can i do this with using only the table view delegates.
This is what i tried:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CustomCell_For_Dashboard";
CustomCellFor_Dashboard *customCell = (CustomCellFor_Dashboard *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (customCell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCellFor_Dashboard" owner:self options:nil];
customCell = [nib objectAtIndex:0];
}
[customCell.howyoulfeelBtn addTarget:self action:#selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
customCell.nameLabel.text = #"test";
customCell.imgView.image = [UIImage imageNamed:#"Default.png"];
// customCell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];
return customCell;
}
-(void)buttonclicked:(id)sender{
NSIndexPath *indexPath = [myTable indexPathForCell:sender];
[myTable beginUpdates];
NSIndexPath *insertPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
[myTable insertRowsAtIndexPaths:[NSArray arrayWithObject:insertPath] withRowAnimation:UITableViewRowAnimationTop];
}
can anyone help me?
I got the same task on one project with just one thing different: There were no buttons, just tapping on cell will expand or collapse it.
There are several things you should edit in your code. First, the button method code will look something like this:
- (void) collapseExpandButtonTap:(id) sender
{
UIButton* aButton = (UIButton*)sender; //It's actually a button
NSIndexPath* aPath = [self getIndexPathForCellWithButtonByMagic:aButton];
//expandedCells is a mutable set declared in your interface section or private class extensiont
if ([expandedCells containsObject:aPath])
{
[expandedCells removeObject:aPath];
}
else
{
[expandedCells addObject:aPath];
}
[myTableView beginEditing];
[myTableView endEditing]; //Yeah, that old trick to animate cell expand/collapse
}
Now the second thing is UITableViewDelegate method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([expandedCells containsObject:indexPath])
{
return kExpandedCellHeight; //It's not necessary a constant, though
}
else
{
return kNormalCellHeigh; //Again not necessary a constant
}
}
Key thing here is to determine if your cell should be expanded/collapsed and return right height in delegate method.
Going off of what #eagle.dan.1349 said, this is how to do it on the clicking of the cell. In storyboard, you also need to set the table cell to clip subviews, otherwise the content that would be hidden will show.
.h
#property (strong, nonatomic) NSMutableArray *expandedCells;
.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.expandedCells containsObject:indexPath])
{
[self.expandedCells removeObject:indexPath];
}
else
{
[self.expandedCells addObject:indexPath];
}
[tableView beginUpdates];
[tableView endUpdates];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat kExpandedCellHeight = 150;
CGFloat kNormalCellHeigh = 50;
if ([self.expandedCells containsObject:indexPath])
{
return kExpandedCellHeight; //It's not necessary a constant, though
}
else
{
return kNormalCellHeigh; //Again not necessary a constant
}
}
Saw this post and just wanted to give my 2 cents as my solution to this is very similar to the chosen answer (the tapping of a whole area).
Many people architect this by using just cells alone, but I believe there is a way to build this that might align better with what people are trying to achieve:
There are headers and there are cells. Headers should be tappable, and then cells underneath the headers would show or hide. This can be achieved by adding a gesture recognizer to the header, and when tapped, you just remove all of the cells underneath that header (the section), and viceversa (add cells). Of course, you have to maintain state of which headers are "open" and which headers are "closed."
This is nice for a couple of reasons:
The job of headers and cells are separated which makes code cleaner.
This method flows nicely with how table views are built (headers and cells) and, therefore, there isn't much magic - the code is simply removing or adding cells, and should be compatible with later versions of iOS.
I made a very simple library to achieve this. As long as your table view is set up with UITableView section headers and cells, all you have to do is subclass the tableview and the header.
Link: https://github.com/fuzz-productions/FZAccordionTableView
I also had a same situation and my solution was to put a button on top of the Section Title with viewForHeaderInSection method.
noOfRows defines how many rows are there in each section and button.tag keeps which button of section is pressed.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIButton *btnSection = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height)];
btnSection.tag = section;
[btnSection setTitle:[sectionArray objectAtIndex:section] forState:UIControlStateNormal];
[btnSection addTarget:self action:#selector(sectionButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
return btnSection;
}
- (void)sectionButtonTapped:(UIButton *)button {
sectionIndex = button.tag;
if (button.tag == 0) {
noOfRows = 3;
} else if (button.tag == 1) {
noOfRows = 1;
} else if (button.tag == 2) {
noOfRows = 2;
}
[self.tableView reloadData];
}
Hope this will help you..

How to set custom background color of UITableViewCell even there's no data inside

I want to accomplish something like this :
see there's only one data but, background color continue until end.
I understand I can do inside tableview delegate of tableView:willDisplayCell:forRowAtIndexPath:. but then it doesn't go to empty cell, hence my empty cell always be white.
I used the following code to display cell alternative color even if cell is not initialized.I have done this work on scrollViewDidScroll as showing below:--
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
UIView *view=[[UIView alloc] initWithFrame:tblView.frame];
view.backgroundColor=[UIColor greenColor];
UIView *cellView;
int y=0;
int i=0;
for (UIView *view in tblView.subviews) {
if ([NSStringFromClass([view class]) isEqualToString:#"_UITableViewSeparatorView"]) {
cellView=[[UIView alloc] initWithFrame:CGRectMake(0, y, 320, 44)];
if (i%2==0) {
cellView.backgroundColor=[UIColor redColor];
}else{
cellView.backgroundColor=[UIColor greenColor];
}
[view addSubview:cellView];
i++;
}
}
tblView.backgroundView=view;
}
And got the correct result on scrolling table view. But the problem is it works when user scrolls the tableView atleast once a time.
If you will get success to fire event on tableView completes its reloading.Then it will be fine.
Here is output I got on scrolling tableView.
I also write this method to call didScrollMethod manually but doesn't seems to work perfectly.
[tblView.delegate scrollViewDidScroll:(UIScrollView*)tblView.superclass];
But calling method like code below absolutely works fine.
- (void)viewDidLoad
{
tblView=[[MyFirstView alloc] init];
tblView.delegate=self;
[tblView setFrame:self.view.frame];
[self.view addSubview:tblView];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated{
[tblView.delegate scrollViewDidScroll:(UIScrollView*)tblView.superclass];
}
Means after loading tableView in viewDidLoad call didScroll in viewDidAppear works fine.
Insert below code if fluctuates first row while scrolling.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view=[[UIView alloc] init];
return view;
}
You have to set the backgroundColor to the contentView of a UITableViewCell.
Sample as below:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"identifier"];
if (cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"identifier"]autorelease];
cell.contentView.backgroundColor= [UIColor greenColor];
}
return cell;
}
To have alternate colors in your cells of tableView, you can do the following;
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"identifier"];
if (cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"identifier"]autorelease];
}
if(indexPath.row % 2)
{
cell.contentView.backgroundColor= [UIColor greenColor];
}
else
{
cell.contentView.backgroundColor= [UIColor yellowColor];
}
return cell;
}
A table with plain style doesn't show rows below the last row so there is no way to produce the desired effect using table view cells. About your only option would be to create a view with the alternating pattern and make the view the table view's footer view.
This view would need to deal with being updated as the number of actual rows in the table changes to/from odd and even. And you need to make it tall enough so if the user scrolls the table up a bunch, the footer still reaches the bottom of the screen.
You can setup some placeholder cells in addition to your cell with 'Monthly meeting', something like:
return amount of rows as 1 + (rows to fill screen) in the tableView:numberOfRowsInSection:
In the tableView:cellForRowAtIndexPath: - check for index path of the cell, if its row = 0, then this is your action cell, otherwise, update cells background, do the same in the tableView:willDisplayCell:forRowAtIndexPath:. Make sure to remove selectionStyle for your placeholder cells.
Or, you can use 2 cells - first one - again, your 'Monthly meeting' cell, and second one - a cell with height enough to cover screen from first cell to the bottom with image of striped cells.
This is simple to do. Just have as many items in your data source array as you want to see rows, and have all but the first one be empty strings. In willDisplayCell:forRowAtIndexPath: apply a background color to all the odd numbered cells.
- (void)viewDidLoad {
[super viewDidLoad];
self.theData = #[#"Monthly Meeting",#"",#"",#"",#"",#"",#"",#"",#"",#""];
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row % 2 == 1) {
cell.backgroundColor = [UIColor colorWithRed:232/255.0 green:238/255.0 blue:222/255.0 alpha:1];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = self.theData[indexPath.row];
return cell;
}
Set backgroundColor to the contentView of a UITableViewCell with the help of simple mathematics, Example:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"identifier"];
if (cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"identifier"]autorelease];
if (i%2==0) {
cell.contentView.backgroundColor= [UIColor greenColor];
}else{
cell.contentView.backgroundColor= [UIColor redColor];
}
}
return cell;
}

Resources