Expand And Collapse UITableview - iphone

Am using below code for uitableview expand and collapse.Its works fine.But,when i select any section its expand but not collapse the previously expanded section.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
NSLog(#"expanded");
[expandedSections removeIndex:section];
screenTypeReloadCheck = NO;
}
else
{
screenTypeReloadCheck =YES;
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"UITableExpand"]];
cell.accessoryView = imView;
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"UITableContract"]];
cell.accessoryView = imView;
}
}
}
}
Thanks

I've done same thing in my app.. Here is solution ..
in your .h
#import "sampleCustomCell.h"
#interface second : UIViewController <UITableViewDelegate,UITableViewDataSource>
{
NSMutableDictionary *selectedIndexes;
sampleCustomCell *samplCustom;
UITableView *tblTempData;
NSMutableArray *yourAry;
}
#property(nonatomic,retain) sampleCustomCell *samplCustom;
#property (nonatomic,retain) NSMutableArray *yourAry;
#property (nonatomic,retain) IBOutlet UITableView *tblTempData;
#end
in your .m
#synthesize samplCustom;
#synthesize tblTempData;
BOOL isSelected;
int kCellHieght=0;
- (void)viewDidLoad
{
[super viewDidLoad];
yourAry = [[NSMutableArray alloc] initWithObjects:#"1_id",#"2_id",#"3_id",#"4_id",#"5_id",#"6_id",#"7_id",#"8_id",#"9_id",#"10_id", nil];
selectedIndexes = [[NSMutableDictionary alloc] init];
}
#pragma mark TableView with Expand and collapse
- (BOOL)cellIsSelected:(NSIndexPath *)indexPath {
// Return whether the cell at the specified index path is selected or not
NSLog(#"%#", selectedIndexes);
NSNumber *selectedIndex = [selectedIndexes objectForKey:indexPath];
NSLog(#"%#", selectedIndex);
return selectedIndex == nil ? FALSE : [selectedIndex boolValue];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self cellIsSelected:indexPath])
{
kCellHieght = 200; //Expanded height for your customCell xib.
}
else
{
kCellHieght = 130; // Height of your customCell xib
}
return kCellHieght;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [yourAry count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
sampleCustomCell *cell;
if (tableView.tag == 11)
{
cell = (sampleCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"sampleCustomCell"];
NSArray *nib;
for (UIControl *subview in cell.contentView.subviews) {
[subview removeFromSuperview];
}
if(cell == nil)
{
nib = [[NSBundle mainBundle] loadNibNamed:#"sampleCustomCell" owner:self options:nil];
for(id oneobject in nib)
{
if([oneobject isKindOfClass:[sampleCustomCell class]])
{
cell = (sampleCustomCell *)oneobject;
//[cell setIndexpath:indexPath];
//[cell setDelegete:self];
cell.lblProduct.text = [yourAry objectAtIndex:[indexPath row]];
}
}
}
if([self cellIsSelected:indexPath])
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3];
[UIView commitAnimations];
[self performSelector:#selector(showHidden:) withObject:cell afterDelay:0.4];
}
}
return cell;
}
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
isSelected = ![self cellIsSelected:indexPath];
[tableView deselectRowAtIndexPath:indexPath animated:TRUE];
BOOL isSelected = ![self cellIsSelected:indexPath];
NSNumber *selectedIndex = [NSNumber numberWithBool:isSelected];
[selectedIndexes removeAllObjects];
[self hideTV:tableView];
[selectedIndexes setObject:selectedIndex forKey:indexPath];
NSLog(#" array %#", selectedIndexes);
[self.tblTempData beginUpdates];
sampleCustomCell *selectedCell = (sampleCustomCell *)[tblTempData cellForRowAtIndexPath:indexPath];
if([self cellIsSelected:indexPath])
{
samplCustom = selectedCell;
[UIView animateWithDuration:15 delay:0.2 options:UIViewAnimationCurveLinear animations:^{NSLog(#"animating");} completion:^(BOOL finished){
NSLog(#"Done 1!");
}];
[UIView commitAnimations];
}
else
{
[UIView animateWithDuration:5 delay:0.2 options:UIViewAnimationCurveLinear animations:^{NSLog(#"animating");} completion:^(BOOL finished){
NSLog(#"Done 1!");
}];
[UIView commitAnimations];
}
[self.tblTempData endUpdates];
[tblTempData reloadData];
}
-(void)hideTV:(UIView *) view{
[tblTempData reloadData];
for (id View in [view subviews]) {
if ([View isKindOfClass:[UITextView class]]) {
[View setHidden:YES];
}
if ([View isKindOfClass:[UITableViewCell class]]) {
UITableViewCell *cell = (UITableViewCell *) View;
[self hideTV:cell.contentView];
}
}
}
-(void) showHidden : (UITableViewCell *)cell{
for (id View in [cell subviews]) {
if ([View isKindOfClass:[UITextView class]]) {
if ([View tag] == 111) {
[View setHidden:NO];
}
}
}
}
Hopr this helps.. happy coding.. Thanks..

TableView section is not collapse but expand. Because, Your currentlyExpanded is always return NO. SO, you are always getting expand.
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
NSLog(#"expanded");
[expandedSections removeIndex:section];
screenTypeReloadCheck = NO;
}
else
{
screenTypeReloadCheck =YES;
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
I do not know how do you set currentlyExpanded value. If you need more help, please share few more lines of code.

Related

UISearchBar + didSelectRowAtIndexPath + cellForRowAtIndexPath

I have the following UITableViewController + UISearchBar setup
#interface FeedTableView : UITableViewController <UISearchBarDelegate,UISearchDisplayDelegate>
{
NSMutableArray *ArrayDatiOriginali;
NSMutableArray *searchData;
UISearchBar *searchBar;
UISearchDisplayController *searchDisplayController;
}
Below the load method
- (void)viewDidLoad
{
[super viewDidLoad];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate=self;
self.tableView.tableHeaderView = searchBar; tableView.
}
To select data/rows when the UISeach appear i use
if(tableView==self.searchDisplayController.searchResultsTableView)
{
NSLog(#"Riga corrente: %i",indexPath.row);
appo=[searchData objectAtIndex:indexPath.row];
}
and it works ok for filtering table view.
But if:
Search view is active (showing filtered result)
I click on a row of the filtered result
Then
didSelectRowAtIndexPath is fired but
in the cellForRowAtIndexPath method the expression
if(tableView==self.searchDisplayController.searchResultsTableView) return FALSE
also if UISearchView is active
Any ideas?
Make Two Arrays.
dataArray & filteredDataArray
& Make a BOOL isFiltered.
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
isFiltered = FALSE;
[searchBar resignFirstResponder];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFiltered)
{
<#YOUR_MODEL#>= [filteredDataArray objectAtIndex:indexPath.row];
}
else
{
<#YOUR_MODEL#>= [dataArray objectAtIndex:indexPath.row];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(isFiltered)
rowCount = [filteredDataArray count];
else
rowCount = [dataArray count];
return rowCount;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// [tableView deselectRowAtIndexPath:indexPath animated:YES];
if(isFiltered)
{
<#YOUR_MODEL#>= [filteredDataArray objectAtIndex:indexPath.row];
}
else
{
<#YOUR_MODEL#>= [dataArray objectAtIndex:indexPath.row];
}
//Pass it to any class or do what ever.
}
To add to the previous answer, you also need to add:
searchBar.delegate = self;
The searchBar will then be able to call
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text

custom tableview cell is not refreshing

This is my custom table view cell, I want to change those values in every 1 minute (values will load from server). I have already set an Nstimer and tried to reload the tableview. Data in my array is changing fine, but value in the uitableviewcell is not changing.
Code:
Tableviewcontroller.m
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
listtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 // start timer ( interval 2 secs )
target:self
selector:#selector(reloadlist:)
userInfo:nil
repeats:YES];
}
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
//UITableView *tv = (UITableView *)self.view;
[self.tableview reloadData];
// NSIndexPath *a = [NSIndexPath indexPathForRow:0 inSection:0]; // I wanted to update this cell specifically
// NearestListCell *c = (NearestListCell *)[tv cellForRowAtIndexPath:a];
//c.count=[usercount objectAtIndex:0];
//[tv beginUpdates];
//// [tv reloadRowsAtIndexPaths:usercount withRowAnimation:UITableViewRowAnimationRight];
//[tv endUpdates];
// [tv reloadData];
}
#pragma mark - Table view data source
- (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.
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Viewcontroller.h
#interface Viewcontroller : UIViewController
{
Tableviewcontroller *Tablecontroller;
IBOutlet UITableView *myTable;
}
#end
Viewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
if (Tablecontroller == nil)
{
Tablecontroller = [[Tableviewcontroller alloc] init];
}
[myTable setDataSource:Tablecontroller];
[myTable setDelegate:Tablecontroller];
Tablecontroller.view = Tablecontroller.tableView;
}
Please try this code : its working fine here
/* FirstTVContoller.h */
#import <Foundation/Foundation.h>
#interface FirstTVContoller : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *items;
}
#end
/* FirstTVContoller.m */
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#implementation FirstTVContoller
-(void) loadView
{
if (items == nil) {
items = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[items objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
[items removeObjectAtIndex:indexPath.row];
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void) dealloc
{
[items release];
[super dealloc];
}
#end
/* SecondTVController.h */
#import <Foundation/Foundation.h>
#interface SecondTVController : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
int numberOfCells;
}
#end
/* SecondTVController.m */
#import "SecondTVController.h"
#implementation SecondTVController
-(void) viewDidLoad
{
numberOfCells = 20;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return numberOfCells;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"2.%d", indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
numberOfCells -=1;
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
}
#end
/* TwoTableViewsViewController.h */
#import <UIKit/UIKit.h>
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#interface TwoTableViewsViewController : UIViewController{
FirstTVContoller *firstController;
SecondTVController *secondController;
IBOutlet UITableView *firstTable;
IBOutlet UITableView *secondTable;
}
#end
/* TwoTableViewsViewController.m */
#import "TwoTableViewsViewController.h"
#implementation TwoTableViewsViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)dealloc {
[firstController release];
[secondController release];
[firstTable release];
[secondTable release];
[super dealloc];
}
Let me know if you still face any problems. This will work for sure for n-no. of UITableViews.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UITableViewController
#end
ViewController.m
#import "ViewController1.h"
#implementation ViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
[self.tableView reloadData];
}
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
listtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 // start timer ( interval 2 secs )
target:self
selector:#selector(reloadlist:)
userInfo:nil
repeats:YES];
}
Please try this code and let me know if you face any problems.Thanks
Why don't you try
[self.tableView reloadData];
instead of
UITableView *tv = (UITableView *)self.view;
[tv reloadData];
Only if your super class is UITableViewController.If not then make an outlet for tableView and reload table through it.
have you used this 'setNeedsDisplay' as
[cell.data11 setNeedsDisplay] if cellForRow is calling.
Please change below code :
/* TwoTableViewsViewController.m */
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadData:) name:#"ReloadFirstTable" object:nil];
}
-(void)reloadData:(id)sender
{
[firstTable reloadData];
}
/* FirstTVContoller.m */
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
self.items = [NSMutableArray arrayWithObjects:#"data1",#" data2 ", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadFirstTable" object:nil];
}
Please use NSNotificationCenter to reload Data.
I fixed the issue. Forgot to reload UITableview object in viewcontroller. I removed the NStimer from Tableviewcontroller.m and placed it in the Viewcontroller.m.
The changed code:
TableViewController.m
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
**// removed the nstimer from here.**
}
#pragma mark - Table view data source
- (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.
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Added these 2 lines of code here.
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:[parsejson getNearestUsercount:[defaults valueForKey:#"userid"]],#" 0 ", nil];
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Viewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
if (Tablecontroller == nil)
{
Tablecontroller = [[Tableviewcontroller alloc] init];
}
[myTable setDataSource:Tablecontroller];
[myTable setDelegate:Tablecontroller];
Tablecontroller.view = Tablecontroller.tableView;
// I Put the Nstimer here.
aTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 // start timer ( interval 2 secs )
target:self
selector:#selector(timerTicked:)
userInfo:nil
repeats:YES];
}
- (void)timerTicked:(NSTimer*)timer
{
[myTable.self reloadData];
}
Thank You all for helping me.

How to grayout all tableview cells except selected one

I have a table view with custom cells ,there are uibuttons on custom cell ,if i select button except that cell remaining all cells should be grayouted or disabled is it possible.
// code in tableview class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
NSLog(#"No OF rows:%d",[contents count]);
return [contents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellIdentifier = #"cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
cell = (uploadCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"uploadCustomCell"];
if (cell == nil) {
NSLog(#"cell allocated");
// Use the default cell style.
cell = [[uploadCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"uploadCustomCell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"uploadCustomCell"
owner:self options:nil];
cell = [nib objectAtIndex:0];
}
saveBtnCcell.hidden = YES;
cell.textNamefield.hidden = YES;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.defaultSwitch setEnabled:NO];
dictionaryContents = [contents objectAtIndex:indexPath.row];
NSLog(#"dict dict :%#",dictionaryContents);
//
cell
.nameLabelCell.text = [dictionaryContents valueForKey:#"VideoName"];
cell.userName.text = [dictionaryContents valueForKey:#"User"];
NSLog(#"Array Image:%#",arrayimage);
cell.thumbImg.image = [arrayimage objectAtIndex:indexPath.row];
NSLog(#"ARimage:%#,index%d",[arrayimage objectAtIndex:indexPath.row],indexPath.row);
NSString *defaultVideo = [dictionaryContents valueForKey:#"DefaultVideo"];
NSLog(#"Default Video:%#",defaultVideo);
if ([defaultVideo isEqual: #"1"]) {
// [cell.defaultSwitch setOn:YES animated:YES];
[defaultSwitche setOn:YES animated:YES];
}
else{
// [cell.defaultSwitch setOn:NO animated:YES];
[defaultSwitche setOn:NO animated:YES];
}
[cell.defaultSwitch addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
VideoNameTextField.hidden = YES;
return cell;
}
// Code in customcell
#interface uploadCustomCell (){
UploadAllViewController *uploadAll;
}
#end
#implementation uploadCustomCell
#synthesize textNamefield;
#synthesize savebtn,edit,nameLabelCell,textLabel,uploadBTN;
#synthesize defaultSwitch;
//#synthesize uploadAll;
- (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
}
- (void)dealloc {
[_userName release];
[_thumbImg release];
//[savebtn release];
[textNamefield release];
[nameLabelCell release];
[_test release];
[savebtn release];
[defaultSwitch release];
[uploadBTN release];
[super dealloc];
}
- (IBAction)editAction:(id)sender {
[uploadBTN setEnabled:NO];
uploadAll = [[UploadAllViewController alloc]init];
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:uploadAll.tabelView1];
NSIndexPath *indexPath = [uploadAll.tabelView1 indexPathForRowAtPoint:buttonPosition];
int no = indexPath.row;
NSLog(#"index path :%d",no);
[uploadAll didEditButtonPressed:self];
}
- (IBAction)saveBtnAction:(id)sender {
[uploadBTN setEnabled:YES];
[uploadAll didSaveButtonPressed:self];
}
when i select this editAction: except that cell remaining cells should be grayouted.
In your cellForRowAtIndexPath you have to account for the state of your table view, i.e. if one or zero cells are selected. Use that to change the appearance of your cell as you wish. In the example below I have assumed you are having a straight array without any sections, but the same principle would work with indexPaths as well. I use an int selectedRow set to -1 if there is no cell selected.
#define kNoCellSelected -1
// in cellForRowAtIndexPath:
if (self.selectedRow == kNoCellSelected) {
cell.backgroundView.backgroundColor = normalColor;
cell.userInteractionEnabled = YES;
}
else if (self.selectedRow != indexPath.row) {
cell.backgroundView.backgroundColor = disabledColor;
cell.userInteractionEnabled = NO;
}
Don't forget to set selectedRow in didSelectRowAtIndexPath: and in viewDidLoad.

Inserting row to the section in tableview dyanmically iphone

I am trying to insert row in the section. cell is a custom cell having textfield.
Below is the code snippet,
-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
NSLog(#"row in section::%i %i", section, sectionRows);
if(section == 0)
return 1;
else if(section == 1)
return 1;
else
return sectionRows;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell rows in section%i %i", indexPath.section, [tableView numberOfRowsInSection:indexPath.section]);
static NSString *MyIdentifier = #"MyIdentifier";
MyIdentifier = #"TableView";
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 31)];
[backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg_accordian.png"]]];
CustomMyMedCellView *customCell;
UIView *viewToHide;
if(indexPath.section == 0)
{
customCell = (CustomMyMedCellView *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
if (customCell == nil)
{
NSLog(#"in Section 1::::::");
[[NSBundle mainBundle] loadNibNamed:#"CustomMyMedCellView" owner:self options:nil];
customCell = customMyMedCellView;
[customCell setTextFieldValue:#"Teva Generic Med" editable:NO];
viewToHide= (UIView *)[customCell.contentView viewWithTag:4];
viewToHide.hidden = YES;
}
}else if(indexPath.section == 1)
{
customCell = (CustomMyMedCellView *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
if(indexPath.row == 0)
{
if (customCell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"CustomMyMedCellView" owner:self options:nil];
customCell = customMyMedCellView;
CGRect frame = customCell.textField.frame;
frame.origin.x = 30.0;
customCell.textField.frame = frame;
[customCell setTextFieldValue:#"Accutane Capsules" editable:NO];
viewToHide = (UIView *)[customCell.contentView viewWithTag:2];
viewToHide.hidden = YES;
}
}
}else
{
customCell = (CustomMyMedCellView *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
NSLog(#"in Section 3%#", customCell);
if (customCell == nil)
{
NSLog(#"in Section 3 if");
[[NSBundle mainBundle] loadNibNamed:#"CustomMyMedCellView" owner:self options:nil];
customCell = customMyMedCellView;
customMyMedCellView.textField.delegate = self;
CGRect frame = customCell.textField.frame;
frame.origin.x = 30.0;
customCell.textField.frame = frame;
[customCell setTextFieldValue:#"" editable:YES];
viewToHide = (UIView *)[customCell.contentView viewWithTag:2];
viewToHide.hidden = YES;
viewToHide = (UIView *)[customCell.contentView viewWithTag:4];
viewToHide.hidden = YES;
viewToHide = (UIView *)[customCell.contentView viewWithTag:5];
viewToHide.hidden = YES;
viewToHide = (UIView *)[customCell.contentView viewWithTag:6];
viewToHide.hidden = YES;
customCell.tag = indexPath.row;
[self.myMedsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(sectionRows-1) inSection:2] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
}
if(!self.isEditClicked)
{
viewToHide = (UIView *)[customCell.contentView viewWithTag:1];
viewToHide.hidden = YES;
}else{
viewToHide = (UIView *)[customCell.contentView viewWithTag:1];
viewToHide.hidden = NO;
}
customCell.backgroundView = backgroundView;
return customCell;
}
on clicking button i want to add row to section 2, for that below is the code i have added,
- (void)addButtonClick:(id)sender {
UIButton *clickedButton = (UIButton *) sender;
if(clickedButton.tag == 2)
{
NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
NSInteger rowsInSection = [self.myMedsTableView numberOfRowsInSection:2];
if(rowsInSection>0){
NSLog(#"%#", [[self.myMedsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowsInSection-1 inSection:2]] viewWithTag:rowsInSection-1 ]);
CustomMyMedCellView *uiView = (CustomMyMedCellView *)[[self.myMedsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowsInSection-1 inSection:2]] viewWithTag:rowsInSection-1 ];
// NSLog(#"%#", uiView.subviews);
// UITextField *textField = (UITextField *)[uiView viewWithTag:3];
if([uiView.textField .text length] > 0)
{
sectionRows+=1;
}
}else{
sectionRows=1;
}
NSLog(#"Sectipn rows::::%i", sectionRows);
for (NSInteger i = 0; i < sectionRows; i++) {
NSLog(#"Sectipn rows:::: inside for");
[indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:2]];
}
NSLog(#"%i",[indexPathsToInsert count]);
[self.myMedsTableView beginUpdates];
[self.myMedsTableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationBottom];
[self.myMedsTableView endUpdates];
//[self.myMedsTableView reloadData];
}else{
Search *tableViewController = [[Search alloc] initWithNibName:#"Search" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:tableViewController animated:YES];
}
But i am getting below error,
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 2. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (2 inserted, 0 deleted).'
Please help me i am new to the iphone.
Thanks in Advance
This error occurs because there is inconsistency between the cells that are given through "cellForRowAtIndexPath" and the index paths you are trying to update. When updating your table with new cells, make sure that your "cellForRowAtIndexPath" can create a cell for these indexes and also make sure that the numberOfRowsInSection is also consistent with this information.

will lead to "Program received signal: “SIGKILL”."

I have a UITableView, where I extend/shrink the cells with the following code.
I save the last 2 indexPaths to perform a reloadRowsAtIndexPaths: on it.
Now I added a UISearchBar to the header for section 0. If I tab the searchBar, a KeyBoard is displayed on top of the UITableView — so far so good.
But I want the user to be able to touch the Cells and disable the KeyBoard. To do so, I test if the searchbox is the first responder inside the -tableView:didSelectRowAtIndexPath:
But doing so will lead to a "SIGKILL" in one of the rows marks 1, 2, 3
I really don't understand why
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Article *article = [articles objectAtIndex:indexPath.row];
ArticleCell *cell = (ArticleCell*)[self.tableView dequeueReusableCellWithIdentifier:#"articelcell"];
if (cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:#"ExtendibleCell" owner:self options:nil] objectAtIndex:0];
}
//....
cell.articleName.text = [NSString stringWithFormat:#"%#",article.name ];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([searchBar isFirstResponder]) {
[searchBar resignFirstResponder];
}
[orderTableDelegate receiveSelectedArticleName:[[articles objectAtIndex:indexPath.row] name]];
firstSelected = lastSelected;
lastSelected = indexPath;
if (lastSelected == firstSelected && firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:lastSelected] withRowAnimation:CELL_ANIMATION]; //1
lastSelected = nil;
firstSelected = nil;
return;
}
if (lastSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:CELL_ANIMATION];//2
}
if (firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:firstSelected] withRowAnimation:CELL_ANIMATION];//3
}
}
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section ==0) {
if (searchBar == nil) {
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[searchBar setShowsBookmarkButton:YES];
[searchBar setKeyboardType:UIKeyboardTypeAlphabet];
[searchBar setBarStyle:UIBarStyleBlack];
[searchBar setShowsCancelButton:YES];
[searchBar setDelegate:self];
}
return searchBar;
}
return nil;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath isEqual:lastSelected] && lastSelected!=firstSelected) {
return [[(Article *)[articles objectAtIndex:indexPath.row] sizesAndPrices] count]*PACKAGESIZE_PRICE_BUTTON_HEIGHT +30;
}
return 40.0;
}
edit
I cleaned up my code for -tableView:didSelectRowAtIndexPath:, but the problem stays the same
#property(nonatomic,retain) NSIndexPath *firstSelected;
#property(nonatomic,retain) NSIndexPath *lastSelected;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[orderTableDelegate receiveSelectedArticleName:[[articles objectAtIndex:indexPath.row] name]];
self.firstSelected = nil;
self.firstSelected = self.lastSelected;
self.lastSelected = nil;
self.lastSelected = [indexPath retain];
if (self.firstSelected == self.lastSelected) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:self.firstSelected] withRowAnimation:CELL_ANIMATION];
[self.firstSelected release];
[self.lastSelected release];
self.firstSelected = nil ;
self.lastSelected = nil ;
} else {
if (self.firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:self.firstSelected] withRowAnimation:CELL_ANIMATION];
}
if (self.lastSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:self.lastSelected] withRowAnimation:CELL_ANIMATION];
}
}
if ([searchBar isFirstResponder]) {
[searchBar resignFirstResponder];
}
}
firstSelected = lastSelected;
lastSelected = indexPath;
This leads me to believe that lastSelected is an instance variable? If this is the case, you are not properly retaining it, and there is no guarantee that it is still alive beyond the scope of this method. The indexPath passed in the didSelectRowAtIndexPath: argument needs to be retained if you are going to use it after it's execution.
Keep in mind, if you do that, you need better memory management throughout that method...i.e. releasing lastSelected before changing it's value or setting it to nil.
Assuming firstSelected and lastSelected are instance variables, you could do something like this. (all the releasing and != checking would go away if you made them retained properties and used the setter)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([searchBar isFirstResponder]) {
[searchBar resignFirstResponder];
}
[orderTableDelegate receiveSelectedArticleName:[[articles objectAtIndex:indexPath.row] name]];
if (firstSelected != lastSelected) {
[firstSelected release];
firstSelected = [lastSelected retain];
}
if (lastSelected != lastSelected) {
[lastSelected release];
lastSelected = [indexPath retain];
}
if (lastSelected == firstSelected && firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:lastSelected] withRowAnimation:CELL_ANIMATION]; //1
[lastSelected release];
lastSelected = nil;
[firstSelected release];
firstSelected = nil;
return;
}
if (lastSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:CELL_ANIMATION];//2
}
if (firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:firstSelected] withRowAnimation:CELL_ANIMATION];//3
}
}