After searching a lot did not found a proper solution to update a tableview
i want to update my tableview like a new coming record should place just below the previously updated records.
this is my code
if (sqlite3_open(myDatabase, &myConnection) == SQLITE_OK)
{
sqliteQuery = [NSString stringWithFormat: #"SELECT Description, SalePrice FROM ProductDetails WHERE Barcode = \'%#\'", barcode];
if (sqlite3_prepare_v2(myConnection, [sqliteQuery UTF8String], -1, &sQLStatement, NULL) == SQLITE_OK)
{
if(sqlite3_step(sQLStatement) == SQLITE_ROW)
{
temp = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(sQLStatement, 0)];
}
temp1 = [NSString stringWithFormat:#"%d", value];
if ([temp1 isEqualToString:#"0"])
{temp1 = #"1";}
temp2 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(sQLStatement, 1)] }
}
[description addObject: temp];
[qty addObject: temp1];
[price addObject:temp2];
}
sqlite3_finalize(sQLStatement);
}
sqlite3_close(myConnection);
}
myTable.hidden = NO;
myTable.delegate = self;
myTable.dataSource = self;
[myTable reloadData];
[self.view endEditing:YES];
and the tableview data source delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [description count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
// Configure the cell in each row
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [self getCellContentView:CellIdentifier];
UILabel *lbl11 = (UILabel *)[cell viewWithTag:1];
[lbl11 setText:#"Label1"];
UILabel *lbl21 = (UILabel *)[cell viewWithTag:2];
[lbl21 setText:#"Label2"];
UILabel *lbl31 = (UILabel *)[cell viewWithTag:3];
[lbl31 setText:#"Label3"];
lbl11.text = [description objectAtIndex:indexPath.row];
lbl21.text = [qty objectAtIndex:indexPath.row];
lbl31.text = [price objectAtIndex:indexPath.row];
return cell;
}
- (UITableViewCell *)getCellContentView:(NSString *)cellIdentifier
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
cell.backgroundColor=[UIColor clearColor];
CGRect lbl11Rect = CGRectMake(20, 5, 450, 30);
CGRect lbl21Rect = CGRectMake(545, 5, 150, 30);
CGRect lbl31Rect = CGRectMake(795, 5, 150, 30);
UILabel *lbl11 = [[UILabel alloc] initWithFrame:lbl11Rect];
lbl11.tag=1;
lbl11.font=[UIFont fontWithName:#"Superclarendon" size:15];
lbl11.backgroundColor=[UIColor clearColor];
//lbl11.layer.borderWidth = 1.0f;
[cell.contentView addSubview:lbl11];
UILabel *lbl21 = [[UILabel alloc] initWithFrame:lbl21Rect];
lbl21.tag=2;
lbl21.font=[UIFont fontWithName:#"Superclarendon" size:15];
lbl21.backgroundColor=[UIColor clearColor];
//lbl21.layer.borderWidth = 1.0f;
[cell.contentView addSubview:lbl21];
UILabel *lbl31 = [[UILabel alloc] initWithFrame:lbl31Rect];
lbl31.tag=3;
lbl31.font=[UIFont fontWithName:#"Superclarendon" size:15];
lbl31.backgroundColor=[UIColor clearColor];
//lbl31.layer.borderWidth = 1.0f;
[cell.contentView addSubview:lbl31];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
return cell;
}
for first value search it showed the data in tableview…. how can i update tableview properly
i have found that for update
[myTable beginUpdate]
function will be used… and there is also
insertRowsAtIndexPaths: withRowAnimation
but unfortunately didn't find any good help that how to use this.
any help will be appreciated ….
First update your data source so numberOfRowsInSection and cellForRowAtIndexPath will return the correct values for your post-insert data. You must do this before you insert or delete rows.
Then insert your row:
// First figure out how many sections there are
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
// Then grab the number of rows in the last section
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex];
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
//Adding new data row to last index position:
[myTable beginUpdates];
[myTable insertRowsAtIndexPaths:[NSArray arrayWithObject: pathToLastRow] withRowAnimation:UITableViewRowAnimationNone];
[myTable endUpdates];
There are different variants for animation:
UITableViewRowAnimationBottom
UITableViewRowAnimationFade
UITableViewRowAnimationMiddle
UITableViewRowAnimationNone
UITableViewRowAnimationRight
UITableViewRowAnimationTop
From iOs Developer Library:
beginUpdates
Begin a series of method calls that insert, delete, or select rows and sections of the receiver.
Discussion
Call this method if you want subsequent insertions, deletion, and selection operations (for example, cellForRowAtIndexPath: and indexPathsForVisibleRows) to be animated simultaneously. This group of methods must conclude with an invocation of endUpdates. These method pairs can be nested. If you do not make the insertion, deletion, and selection calls inside this block, table attributes such as row count might become invalid. You should not call reloadData within the group; if you call this method within the group, you will need to perform any animations yourself.
The example of using this method you can find in Related Sample Code: iPhoneCoreDataRecipes
Related
I have a UITableViewController called HighScoreViewController that possesses UITableViewCells that are each individual HighScore objects.
When I press the segmented control at the top I want to resort the TableCells immediately. However, currently my sort only works by dragging around so that the cells are off-screen causing the (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath to be called again (which resorts the individual cell according to the score, duration, or date).
I tried to create a method that would be called in my segmented control action that would remove and add the View to redraw the cells. When that didn't work I tried redrawing each cell manually but I realized that it would be a extremely complicated as I would have to monitor which scores had already been sorted in the View and what scores were sorted in the Data Source. I also tried setNeedsDisplay.
How can I resort the UITableViewCells immediately after pressing the segmented control?
This is my action outlet for the segmented Control
- (IBAction)changeSort:(id)sender {
NSLog(#"changing Sort");
// Sorted by score
if (self.sortingButton.selectedSegmentIndex == SORT_BY_SCORE){
[self sortHighScoresByScore];
}else if (self.sortingButton.selectedSegmentIndex == SORT_BY_DURATION){// sorted by duration
[self sortHighScoresByDuration];
}else if (self.sortingButton.selectedSegmentIndex == SORT_BY_DATE){// sorted by last time played
[self sortHighScoresByDate];
}else{
NSLog(#"HighScoreViewController, changeSort else != 0,1,2");
}
}
And this is my cell method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"HighScoreCell" forIndexPath:indexPath];
NSLog(#"inside TableView");
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"HighScoreCell"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *playingCardHighScores = [defaults objectForKey:#"playingCardHighScores"];
NSMutableArray *setCardHighScores = [defaults objectForKey:#"setCardHighScores"];
// Decode High Scores arrays
playingCardHighScores = [self decodeEncodedArray:playingCardHighScores];
setCardHighScores = [self decodeEncodedArray:setCardHighScores];
/* Will need to set the left and right side to two different scores or add some kind of slider*/
HighScore *hs = playingCardHighScores[indexPath.row];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(55, 4, 260, 20)];
label.font = [UIFont boldSystemFontOfSize:15.0];
label.tag=25;
UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 25, 260, 15)];
detailLabel.adjustsFontSizeToFitWidth = YES;
detailLabel.tag=30;
NSString *score = [NSString stringWithFormat:#"Score:%ld",(long)hs.score];
NSString *duration = [NSString stringWithFormat:#",Duration:%.2f",hs.secondsPlayed];
NSString *datePlayed = [NSString stringWithFormat:#",datePlayed:%#",hs.datePlayed];
NSString *combination = [score stringByAppendingString:[duration stringByAppendingString:datePlayed]];
detailLabel.text = combination;
[cell.contentView addSubview:label];
[cell.contentView addSubview:detailLabel];
// Should change depending on what selector is picked
NSString *strScore;
NSDate *date;
switch (self.sortingButton.selectedSegmentIndex) {
case SORT_BY_SCORE:
strScore = [NSString stringWithFormat:#"Score: %ld",(long)hs.score];
break;
case SORT_BY_DURATION:
strScore = [NSString stringWithFormat:#"Duration: %.2f seconds",hs.secondsPlayed];
break;
case SORT_BY_DATE:
date = hs.datePlayed;
break;
default:
break;
}
// if the string exists
if (strScore){
cell.textLabel.text = strScore;
}else{
cell.textLabel.text = [date description];
}
return cell;
}
You'll need to call [self.tableView reloadData] in your segmented control IBAction to get all the cells on screen to be recreated.
Alternatively if you want to be able to specify stock animation, you can call reloadSections:withRowAnimation: on your table view
In my iOS app, I want to fresh the entire contents of a tableView when the viewController is loaded. Each cell of a tableView has a textLabel that is the name of a step object.
I've ensured that when I return to the viewController, the correct stepNames are loaded (I know this by logging the names of the steps). However, the name of the step is not updated in the tableView.
How can I ensure that the labels of the tableView cells are loading properly?
How I try to trigger a refresh of the TableView:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
if(reloadSteps == YES){
NSLog(#"reloading steps");
NSData * stepsData = [NSData dataWithContentsOfURL:stepsURL];
[self fetchProjectSteps:stepsData];
[self.projectInfo reloadData];
int numRows = [stepNames count];
NSLog(#"numRows %i", numRows);
for(int i =0; i<numRows; i++){
[self tableView:self.projectInfo cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
}
How each cell of the tableView is rendered:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"in cellForRowAtIndexPath");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"StepCell"];
}
if (indexPath.row ==0) {
cell.textLabel.font = [UIFont systemFontOfSize:16];
cell.textLabel.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
cell.textLabel.text = #"Project Description";
cell.textAlignment = NSTextAlignmentCenter;
} else {
cell.userInteractionEnabled = YES;
cell.textLabel.font = [UIFont systemFontOfSize:16.0];
cell.textLabel.text = [stepNames objectAtIndex:indexPath.row];
NSLog(#"textLabel: %#", cell.textLabel.text); // THIS IS CORRECT, BUT DOES NOT APPEAR TO BE UPDATED IN THE TABLEVIEW
if(![[stepImages objectAtIndex:indexPath.row] isEqual: #""]) {
cell.accessoryView = [stepImages objectAtIndex:indexPath.row];
}
}
return cell;
}
Here is my header file:
#interface EditProjectViewController : UIViewController <UIActionSheetDelegate, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>{
#property (strong,nonatomic) IBOutlet UITableView *projectInfo;
}
and then in my implementation file:
-(void) viewDidLoad{
self.projectInfo = [[UITableView alloc]init];
self.projectInfo.delegate = self;
}
Delete all this:
int numRows = [stepNames count];
NSLog(#"numRows %i", numRows);
for(int i =0; i<numRows; i++){
[self tableView:self.projectInfo cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
}
Your reloadData call will call cellForRowAtIndexPath: for every cell in your table view. Just make sure you're returning stepNames.count for numberOfRowsInSection:.
EDIT
I've looked over your updated code. A couple things (including what your problem most likely is):
Your projectInfo outlet should be weak, not strong (since it's an IBOutlet)
Even though you have your table view linked up in the interface file, you're initializing it in viewDidLoad, creating a new instance
Change the following:
-(void) viewDidLoad{
self.projectInfo = [[UITableView alloc]init];
self.projectInfo.delegate = self;
}
To this:
-(void) viewDidLoad{
self.projectInfo.dataSource = self;
self.projectInfo.delegate = self;
}
I have problem with my UItableview that when I use viewWillAppear for retrieving updated data each time table is viewed this gives me exception .
Please can any one help me on how to refresh tableview in viewWillAppear so that it will be updated before CellforrowAtindexPath is called ?
Here is my code for viewWillAppear:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[self.tableView reloadData];//table was filled in viewDidLoad.
}
Here is CellforrowAtindexPath` : (The exception is on mainArray which means that there is conflict in updating table through viewWillAppear and calling cell ):
//Methods to retrive all selected words , thier sound and picture for the mother
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifer = #"Cell";
UITableViewCell *cell= [ tableView dequeueReusableCellWithIdentifier:CellIdentifer];
cell.textLabel.font = [UIFont systemFontOfSize:17.0];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifer];
}
cell.textLabel.font = [UIFont systemFontOfSize:17.0];
UILabel *label ;
label=(UILabel *)[cell viewWithTag:1];
NSString *value = [[self.mainArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
label.text = value;
label.textAlignment=NSTextAlignmentRight;
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
//self.tableView.separatorColor = [UIColor blackColor];TRY TO SEPARETE BETEWEEN LINES OF TABLE
UIButton *butt =(UIButton *)[cell viewWithTag:2];
NSString *value2 = [[self.mainArray2 objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
butt.restorationIdentifier= value2;
[butt addTarget:self action:#selector(play:) forControlEvents:UIControlEventTouchUpInside];
NSString *value3 = [[self.mainArray3 objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:value3];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
return cell;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;{
return self.mainArray.count;
}
if count is 0, table view won't call the other functions.
I have a problem with my UISwitch inside a UITableViewCell. When I change the value of one switch then scroll up or down all switches are messed up. I use an array to store state for each switch due to reusability they are still messed up every time.
Here is cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Cell"];
}
UISwitch *switchController = [[UISwitch alloc] initWithFrame:CGRectZero];
CGRect switchFrame = switchController.frame;
[switchController setOn:YES animated:NO];
//set its x and y value, this you will have to determine how to space it on the left side
switchFrame.origin.x = 50.0f;
switchFrame.origin.y = 10.0f;
switchController.frame = switchFrame;
[switchController addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[cell addSubview:switchController ];
UILabel *label ;
label=(UILabel *)[cell viewWithTag:1];
NSString *value = [[mainArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
label.text = value;
label.textAlignment = NSTextAlignmentRight;
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
//This for persist switch state when scroll up or down
if ([[[self.SwitchArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row ]isEqualToString:#"ON"])
{
switchController.on=YES;
}
else
{
switchController.on=NO;
}
return cell;
}
Here is SwitchChanged event :
-(void)switchChanged:(UISwitch *)sender
{
UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *index=[mainTableView indexPathForCell:cell];
if (sender.on)
{
[[self.SwitchArray objectAtIndex:index.section] replaceObjectAtIndex:index.row withObject:#"ON"];
NSString *word= [[self.mainArray objectAtIndex:index.section ] objectAtIndex:index.row];
}
else
{
//call the first array by section
[[self.SwitchArray objectAtIndex:index.section] replaceObjectAtIndex:index.row withObject:#"OFF"];
NSString *word= [[self.mainArray objectAtIndex:index.section ] objectAtIndex:index.row];
}
[padFactoids setObject:[NSKeyedArchiver archivedDataWithRootObject:SwitchArray] forKey:#"savedArray"];
[padFactoids synchronize];
}
I will appreciate your help so much.
In your header file declare an NSMutableArray, let's name it switchStates.
In your viewDidLoad, allocate memory and add object with the string "OFF" according to number of switches:
switchStates = [[NSMutableArray alloc] init];
for (int i; i <= switchesArray.count; i++) {
[switchStates addObject:#"OFF"];
}
In your method which runs when the switch is triggered:
NSString *theSwitchPosition = [NSString stringWithFormat:#"%#", switchControl.on ? #"ON" : #"OFF"];
[switchStates replaceObjectAtIndex:aPath.row withObject:theSwitchPosition];
After that, in the method where you create your switches:
if ([[switchStates objectAtIndex:indexPath.row] isEqualToString:#"ON"]) {
mySwitch.on = YES;
} else {
mySwitch.on = NO;
}
This worked for me, good luck..
I am not sure whether this causes your problem, but it will certainly cause other related problems.
Each time when a cell was moved off screen and a next one appears, the one that just moved off screen will be reused.
But you add a new switch object every time to the cell. You are far better off creating those only within the cell==nil block. Give it a tag and use the tag to fetch the object upon reusage as you do with the lable object.
You're creating a new switch every time the tableView is asking for a cell. You only want to create the switch once for each cell:
UISwitch *switchController;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Cell"];
switchController = [[UISwitch alloc] initWithFrame:CGRectZero];
CGRect switchFrame = switchController.frame;
[switchController setOn:YES animated:NO];
//set its x and y value, this you will have to determine how to space it on the left side
switchFrame.origin.x = 50.0f;
switchFrame.origin.y = 10.0f;
switchController.frame = switchFrame;
[switchController addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[cell.contentView addSubview:switchController ];
switchController.tag = 123; //Arbitrary number...can be anything
}
else {
switchController = (UISwitch *)[cell.contentView viewWithTag:123];
}
//Now set the switch state according to your data model array
It's also generally a better practice to add subviews to the cell's contentView rather than the cell itself.
i have a tableview. i add image to the cells when clicked on the cell in didselectrow method by using cell.conteview addsubview. but the problem is if i click on 1st cell it changes the image and when i click on another cell image will appears but the old image is not removed from the previous cell. This is happening for all cells in table view if a cell is clicked.
i used the code as follows
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
Practices *bPractices = [topics objectAtIndex:indexPath.row];
UIImageView *clickView;
//[cell.contentView removeFromSuperview];
clickView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 315, 82)];
clickView.image = [UIImage imageNamed:#"list_bg_hover.png"];
[cell.contentView addSubview:clickView];
[clickView release];
UILabel *labelText= [[UILabel alloc]initWithFrame:CGRectMake(90, 30, 320, 20)];
labelText.text=bPractices.practices_title;
labelText.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:labelText];
}
pls help me how to solve this issue
Thanks in advance
I did something similar, but not with images but buttons. If a cell wasn't selected yet and gets tabbed, the size is changed and a certain and individual number of buttons is added. If another cell was selected, this one gets closed.
Code from form the UITableViewController
interface:
int openedCellIndex;//<-what cell is selected
int buttonCounter;
implementation:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( indexPath.row != openedCellIndex )
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TRTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier]
autorelease];
//cell.frame = CGRectMake (0,0, 320, 100);
}
id <P_E_P1Article> article = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = article.name;
if ( self.cellBackgroundColor )
cell.backgroundColor = self.cellBackgroundColor;
return cell;
}
else {
//get article
id <P_E_P1Article> article = [self.fetchedResultsController objectAtIndexPath:indexPath];
//number of buttons
int buttons = [article.specification count];
int height = 50 * ceil(buttons / 2) + 50;
//construct special cell
UITableViewCell *cell = [[[TRTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"CellBig"]
autorelease];
cell.frame = CGRectMake (0,0, 320, 150);
cell.textLabel.text = #"";
//add label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 280, 30)];
label.font = [UIFont boldSystemFontOfSize:17];
label.text = article.name;
label.backgroundColor = [UIColor clearColor];
[cell addSubview:label];
[label release];
if ( buttonMapper == nil )
self.buttonMapper = [NSMutableDictionary dictionaryWithCapacity:10];
//NSLog (#" bla: %#", article.isFreePrice);
//see if we have a free prized article
//create the buttons
NSEnumerator *enumerator = [article.specification objectEnumerator];
id <P_E_P1ArticleSpecification> spec;
int count = 0;
NSArray *specs =
[self sortedArticleSpecifications:article];
for ( spec in specs ) {
//see which row and col the button is in
int row = floor ( count / 2 );
int col = count % 2;
//define button position
int left = 20 + col * 145;
int top = 45 + row * 50;
//create button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(left, top, 135, 40);
[cell addSubview:button];
[button setTitleColor:[UIColor blackColor] forState:0];
[button addTarget:self
action:#selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
//remember which article the button is attached to
buttonCounter++;
button.tag = buttonCounter;
[buttonMapper setValue:spec forKey:[NSString stringWithFormat:#"bla%d",buttonCounter]];
count++;
}
if ( self.cellBackgroundColor )
cell.backgroundColor = self.cellBackgroundColor;
return cell;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( openedCellIndex == indexPath.row )
{
id <P_E_P1Article> article = [self.fetchedResultsController objectAtIndexPath:indexPath];
int count = [article.specification count];
int height = 50 * ceil(count / 2.) + 50;
return height;
}
return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self openRow:indexPath.row];
[self.searchBar resignFirstResponder];
}
- (void) openRow:(int) index
{
if ( index == openedCellIndex ) return;
int oldIndex = openedCellIndex;
openedCellIndex = index;
NSUInteger indexArr[] = {0, oldIndex};
NSIndexPath *oldPath = [NSIndexPath indexPathWithIndexes:indexArr length:2];
NSUInteger indexArr2[] = {0, openedCellIndex};
NSIndexPath *newPath = [NSIndexPath indexPathWithIndexes:indexArr2 length:2];
//update view
[(UITableView *)self.view beginUpdates];
if ( oldIndex >= 0 )
[(UITableView *)self.view reloadRowsAtIndexPaths:[NSArray arrayWithObject:oldPath]
withRowAnimation:UITableViewRowAnimationFade];
if (openedCellIndex >=0 )
[(UITableView *)self.view reloadRowsAtIndexPaths:[NSArray arrayWithObject:newPath]
withRowAnimation:UITableViewRowAnimationFade];
[(UITableView *)self.view endUpdates];
}
You could also subclass UITableViewCell and handle the select/deselect process in the setSelected method. Then use your custom cell as the type for the prototype cell instead of the default.