uiTableViewCell Add row with and image and remove row with second tap - ios

I've been trying to figuered this out for hours. I'm just plain old stuck here. What im trying to accomplish is basically inserting a row directly below the row just tapped in the tableview in addition i would like to add and image to the row and and make the image clickable to respond to its click event.
So here is my code.
I implemented (i belive) the nessesary methods to handle all the actions for the uitableview.
when the user taps the cell i handle that action by executing the following code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debug==1) {
NSLog(#"running line 225%# '%#'", self.class, NSStringFromSelector(_cmd));
}
Locations *location = nil;
Locations *tempObject = [[Locations alloc]init];
//test to see if we are looking for the search box or if we are essentially looking from the main view controller.
if (self.searchDisplayController.active) {
location= [self.searchResults objectAtIndex:indexPath.row];
NSLog(#"location : %#" ,location.locationName);
} else {
location = [self.locations objectAtIndex:indexPath.row];
NSLog(#"location : %#" ,location.locationName);
//set the new indexpath to 1 more then before so that we can essetially add a row right below the actual tapped item.
NSIndexPath *newPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
indexPath = newPath;
[self.locations insertObject:tempObject atIndex:indexPath.row ];
[tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
self.visibleCell =YES; //set this boolean variable so that we can add a specific row image to this var
// self.locations[0].isItVisible = YES;
}//ends the else statement.
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
the above code inserts an empty cell into my tableview.
however how can i set the cell so that its custom and not the same as the others. In other words my initial cells data-source are basically bound to an nsobject and a string property location-name. However when i go try to update the table cells in the above method i obviously cannot add an image into a string so I'm running in to a error.
so i tried to instead make the update on the
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
by basically checking if a variable is set to true or false but that turned out to be buggy because even when i scroll this method gets called.
How should i go about doing this. I think i have to do it all in the didselectrowindexaspath method. But i cant figured out how to change the newly inserted cell to contain an image only.
Any help would be appreciated.
EDIT
here is what im doing to try to add the image under the cellforrowindexpath method.
if(self.visibleCell==YES){
UIImage *clkImg = [UIImage imageNamed:#"alarm_clock.png"];
cell.imageView.image = clkImg;
}
Im a noob so im not sure im doing this correctly.
EDIT
this is the full cellforatindexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debug==1) {
NSLog(#"running line 159 %# '%#'", self.class, NSStringFromSelector(_cmd));
}
// NSLog(#"cell for row at index path just got called");
//JAMcustomCell *myCell = [[JAMcustomCell alloc]init];
static NSString *CellIdentifier = #"ListPrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Locations * locations = [[Locations alloc]init];
//tableView.backgroundColor = [UIColor blackColor];
// NSLog(#"this is visible '%hhd'", locations.isItVisible);
if(self.visibleCell==YES){
UIImage *clkImg = [UIImage imageNamed:#"alarm_clock.png"];
cell.imageView.image = clkImg;
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
locations = [self.searchResults objectAtIndex:indexPath.row];
}
else{
locations = [self.locations objectAtIndex:indexPath.row];
}
cell.textLabel.text = locations.locationName;
cell.textLabel.textColor = [UIColor whiteColor];
//cell.backgroundColor =[UIColor blackColor];
// cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"Graytbl.fw.png"]];
cell.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"blueTbl.fw.png"]];
cell.selectedBackgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"blueTbl.fw.png"]];
// UIFont *myFont = [ UIFont fontWithName: #"Oswald" size: 25.0 ];
// cell.textLabel.font = myFont;
cell.textLabel.font= self.MyFont;//[UIFont fontWithName:#"Oswald-Regular.ttf" size:15];
return cell;
}

Try this approach, I used your idea of Bool
#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.visibleCell){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"imageViewCell" forIndexPath:indexPath];//ListPrototypeCell
UIImageView *imageVIew = (UIImageView *)[cell viewWithTag:1];
[imageVIew setImage:[UIImage imageNamed:#"alarm_clock.png"]];
return cell;
}else{
return [tableView dequeueReusableCellWithIdentifier:#"ListPrototypeCell" forIndexPath:indexPath];
}
}
#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(!self.visibleCell){
self.numberOfRows++;
self.visibleCell = YES;
NSIndexPath *indexPathCell = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPathCell] withRowAnimation:UITableViewRowAnimationBottom];
}else{
self.numberOfRows--;
self.visibleCell = NO;
NSIndexPath *indexPathCell = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView deleteRowsAtIndexPaths:#[indexPathCell] withRowAnimation:UITableViewRowAnimationTop];
}
}
I created a demo project for you.
I hope it helps

Related

Section header is repeating when UITextView size is increased in UITableView Cells

I have been playing around with this problem since a day and I have tried many ways to resolve this issue but have not yet succeeded. I have a tableview with 3 custom cells and I have added section header for last two sections. Here is the screen shot.
which shows last section header is repeating when I enter text in the TextView. My TextView is editable and I have disabled the scrolling to adjust the size of the textview as per the text size.
Here is the code.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *titleArray = #[#"",#"About You",#"Gender"];
NSString *titleHeading = [titleArray objectAtIndex:section];
return titleHeading;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return section == 0 ? CGFLOAT_MIN : 35;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = [NSString stringWithFormat:#"cell%ld,%ld",indexPath.section, indexPath.row];
id cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (indexPath.section == 1)
{
ProfileAboutCell *cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cellObj)
{
[_tableView registerNib:[UINib nibWithNibName:#"ProfileAboutCell" bundle:nil] forCellReuseIdentifier:identifier];
cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
}
cellObj.selectionStyle = UITableViewCellSelectionStyleNone;
//[cellObj.txtAboutYou layoutIfNeeded];
cellObj.txtAboutYou.delegate = self;
cellObj.lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 0.0,cellObj.txtAboutYou.frame.size.width - 10.0, 34.0)];
cellObj.lbl.text = #"About You";
[cellObj.lbl setBackgroundColor:[UIColor clearColor]];
[cellObj.lbl setTextColor:[UIColor lightGrayColor]];
[cellObj.txtAboutYou addSubview:cellObj.lbl];
// [cellObj.txtAboutYou setText:[kUserDefaults valueForKey:kAbout]];
//[cellObj.txtAboutYou sizeToFit];
cell = cellObj;
}
return cell;
}
TextView Delegate Method.
-(void)textViewDidChange:(UITextView *)textView
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
ProfileAboutCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
if(![textView hasText]) {
cell.lbl.hidden = NO;
}
else{
cell.lbl.hidden = YES;
}
NSInteger len = textView.text.length;
cell.lblChar.text=[NSString stringWithFormat:#"%li",500-len];
[_tableView beginUpdates];
[_tableView endUpdates];
}
I have tried this #SO solution but no help. Any help would be much appreciated in this direction. Thanks in advance.
From my understanding of the issue you can solve it by set the sections headers in "titleForHeaderInSection" the same way you set the cells in "cellForRowAtIndexPath" for each section,
this way sections that you don't set Headers for will not cause any issue.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *titleArray = #[#"",#"About You",#"Gender"];
if (indexPath.section == 1) {
NSString *titleHeading = [titleArray objectAtIndex:1];
return titleHeading;
}
if (indexPath.section == 2) {
NSString *titleHeading = [titleArray objectAtIndex:2];
return titleHeading;
}
}

Keep selected state of UITableViewCells when scrolling

I am trying to keep the selected state of multiple cells on a didSelectRowAtIndexPath method. I have an edit button that I've set up that loops through every cell to select each field on my UITableView.
Here is the code for the edit button on tap that selects all my rows.
- (IBAction)editButtonTapped:(id)sender {
for (int i = 0; i < self.caseDataTableView.numberOfSections; i++) {
for (NSInteger r = 0; r < [self.caseDataTableView numberOfRowsInSection:i]; r++) {
[self tableView:caseDataTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:r inSection:i]];
}
}
}
When calling the didSelectRowAtIndexPath method, it does the following code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
OKOperatieNoteTableViewCell *cell = (OKOperatieNoteTableViewCell *)[self.caseDataTableView cellForRowAtIndexPath:indexPath];
cell.cellIndexPath = indexPath;
[cell hideLabelAndShowButtons];}
Incase you were wondering here is the hideLabelAndShowButtons method.
- (void)hideLabelAndShowButtons {
self.caseDataKeyLabel.hidden = NO;
if (!self.disabled) {
self.caseDataValueLabel.hidden = YES;
self.textField.hidden = NO;
if ([self.inputType isEqualToString:#"switcher"] || [self.inputType isEqualToString:#"multiselect"] || [self.inputType isEqualToString:#"picker"] || [self.inputType isEqualToString:#"DatePicker"] || [self.inputType isEqualToString:#"selectContact"]) {
self.button.hidden = NO;
}else {
self.button.hidden = YES;
}
}
self.caseDataDescriptionTextView.hidden = YES;}
Now at this point, I have all my rows selected. If I scroll down and then back up the selection of these rows is not there anymore. Now I'm aware when you go in and out of the view, the cellForRowAtIndexPath method recreates these cells. The following is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"caseData";
OKOperatieNoteTableViewCell * cell = [[OKOperatieNoteTableViewCell alloc]init];
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (indexPath.row < _procedureVariables.count) {
if ([[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] isEqualToString:#"Procedure"]) {
[cell setLabelsWithKey:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] AndValue:[self.model valueForKey:#"var_procedureName"]];
}else {
[cell setLabelsWithKey:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] AndValue:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"value"]];
}
OKProcedureTemplateVariablesModel *variableModel = _procedureVariables[indexPath.row];
cell.variable = variableModel.value;
[cell showLabelAndHideButtons];
cell.delegate = self;
[cell setUpCellType];
} else if (indexPath.row == _procedureVariables.count) {
NSString *text = [NSString stringWithFormat:#"%# \n\n %#", [_templateDictionary objectForKey:#"indicationText"], [_templateDictionary objectForKey:#"procedureText"] ];
[cell showDescription:text];
NSLog(#"cell.caseDataDescriptionTextView.font.fontName = %#", cell.caseDataDescriptionTextView.font.fontName);
}
cell.procedureID = _procedureID;
[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];
return cell;
}
I'm just trying to figure out how to keep the selected state of these cells once the cellForRowAtIndexPath method is called. Any suggestions are welcomed.
i tried to simulate your situation, created a customCell and saved the indexpaths of selectedRows in my custom selectedPaths mutable array(initialized in viewDidLoad).
After every click i removed or added related indexpath to my array.
it worked for my case. Hope it helps.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"caseData";
NOTableViewCell *cell = (NOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSLog(#"new cell created for row %d", (int)indexPath.row);
cell = [[[NSBundle mainBundle] loadNibNamed:#"NOTableViewCell" owner:self options:nil] objectAtIndex:0];
}
if ([selectedPaths indexOfObject:indexPath] != NSNotFound) // this cell is in selected state.
{
[cell.textLabel setText:#"This cell selected"];//selected state job.
return cell;
}
[cell.textLabel setText:[NSString stringWithFormat:#"%d", (int)indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([selectedPaths indexOfObject:indexPath] != NSNotFound) {
[selectedPaths removeObject:indexPath];
}
else{
[selectedPaths addObject:indexPath];
}
//[tableView reloadData];
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];//instead of reloading all just reload clicked cell.
}
You need to update the cell to selected and not selected explicitly in both directions in cellForRowAtIndexPath.
If not, the recycled cells will just show the value of the cell the cell was last used for until you change it.
While you are invoking the delegate method in order to call hideLabelAndShowButtons, you aren't telling the table view that you have selected the row;
- (IBAction)editButtonTapped:(id)sender {
for (int i = 0; i < self.caseDataTableView.numberOfSections; i++) {
for (NSInteger r = 0; r < [self.caseDataTableView numberOfRowsInSection:i]; r++) {
NSIndexPath *path=[NSIndexPath indexPathForRow:r inSection:i];
[caseDataTableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
[self tableView:caseDataTableView didSelectRowAtIndexPath:path];
}
}
}
Also, you aren't using the cell selection state in cellForRowAtIndexPath, so you probably need to change some code there too, but I am not sure what the relationship is between selected state and how you want to render the cell.

Checkmark for UITableView is not selecting to all TableViewCell

Trying to implement the checkmark for UITableView.
Checkmark for UITableView Cell is not selecting to all row, when scroll tableview
its not not enable.
Below is my code which i Implemented.
IndexButton is UIButton Class which added index init.
-(void)selectAllAction:(IndexedButton *)sender{
for (int rowIndex = 0; rowIndex < [array_MedicineList count]; rowIndex++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowIndex inSection:0];
UITableViewCell *cell = [tbl_ProductList cellForRowAtIndexPath:indexPath];
IndexedButton *btn_SelectItem = (IndexedButton *)[cell viewWithTag:TAG_SELECTEDITEM];
[btn_SelectItem setBackgroundImage:[UIImage imageNamed:#"checkMark"] forState:UIControlStateNormal];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *productListTableViewCell = #"ProductListTableViewCell";
ProductListTableViewCell *cell = (ProductListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:productListTableViewCell];
if (cell == nil){
cell = [[ProductListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:productListTableViewCell];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
IndexedButton *btn_SelectItem = [IndexedButton buttonWithType:UIButtonTypeCustom];
btn_SelectItem.frame = CGRectMake(10,52,32,32);
[btn_SelectItem setBackgroundImage:[UIImage imageNamed:#"uncheckMark"] forState:UIControlStateNormal];
[btn_SelectItem addTarget:self action:#selector(selectItemAction:)forControlEvents:UIControlEventTouchUpInside];
btn_SelectItem.index = (int)indexPath.row;
btn_SelectItem.tag = TAG_SELECTEDITEM;
[cell addSubview:btn_SelectItem];
}
IndexedButton *btn_SelectItem = (IndexedButton *)[cell viewWithTag:TAG_SELECTEDITEM];
btn_SelectItem.index = (int)indexPath.row;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
#All
Need suggestion, how to go forward to implement the check mark for tableview.
I would suggest you to use cell with accessory view with UITableViewCellAccessoryCheckmark type to show all cells selected/ few cells selected/ none of the cells selected.
Also, you must keep the state for each cell index within a section, whether it's selected or not as
// keeps info for selected rows in a section in mutable index set as
NSMutableIndexSet *selctedCellsInSection;
// initialize the above set instance
selctedCellsInSection = [[NSMutableIndexSet alloc] init];
//Inside cell for row at index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if ([selctedCellsInSection containsIndex:indexPath.row])
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
else
[cell setAccessoryType:UITableViewCellAccessoryNone];
// customize cell as per your requirements
return cell;
}
You need to hold the information about a cell's checkmark whether it needs to be shown or not in selctedCellsInSection set as -
Use [selctedCellsInSection addIndex:rowToSelect]
// to add cell index on which checkmark needs to be shown
Use [selctedCellsInSection removeIndex:rowToUnselect]
// to add cell index on which checkmark should not be shown
After, customizing the data source selctedCellsInSection(which keeps information about selected/ unselected cell) reload the tableview.
Reloading the table will reflect the selected cells with Cell's Accessory Checkmark.
In your case as you need show check mark on all cell, you can do so as-
-(void)showCheckMarkOnAllCells
{
for (int rowIndex = 0; rowIndex < [array_MedicineList count]; rowIndex++)
{
[selctedCellsInSection addIndex: rowIndex];
}
[tableView reloadData];
}
#interface BRNCategoryViewController ()
{
NSMutableArray *arySelectCategory;
NSMutableArray *aryCategory;
}
- (void) viewDidLoad
{
arySelectCategory=[NSMutableArray new];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return aryCategory.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BRNCategoryCell *cell=[[BRNCategoryCell alloc]initWithOwner:self];
if ([arySelectCategory containsObject:[aryCategory objectAtIndex:indexPath.row]])
{
cell.imgBoxView.image=[UIImage imageNamed:#"checkMark"];
}
else
{
cell.imgBoxView.image=[UIImage imageNamed:#"uncheckMark"];
}
cell.lblTitle.textColor=Rgb2UIColor(127, 127, 127);
cell.lblTitle.font=[ASCustomClass FontWithSize:20.0];
cell.lblTitle.text=aryCategory[indexPath.row];
cell.backgroundColor=[UIColor clearColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([arySelectCategory containsObject:[aryCategory objectAtIndex:indexPath.row]])
{
[arySelectCategory removeObject:[aryCategory objectAtIndex:indexPath.row]];
}
else
{
[arySelectCategory addObject:[aryCategory objectAtIndex:indexPath.row]];
}
[tblEventCategory reloadData];
}

Single selection UITableView overlay cell

I'm trying to make custom selection of UITableView cells. To do this I created UIView above my cell and it appear/disappear on touching now. But the problem is that when I press on cell selection appears. If then I select any other row it will be selected too! But it must not. Every previous cell must be deselected but I do only single selection for my UITableView. I'll glad for any help.
Here is my code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"userDataCell";
AVMThemeCell *cell = [self.userContentTable dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[AVMThemeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
AVMDataStore *oneItem = [userContentArray objectAtIndex:indexPath.row];
oneItem = [userContentArray objectAtIndex:indexPath.row];
[cell setGenre:oneItem];
cell.imgView.image = [UIImage imageNamed:imgThemesArray[indexPath.row]];
//save cell state!
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row];
if ([selectedCellsArray containsObject:[NSString stringWithFormat:#"%#",rowNsNum]] )
{
NSLog(#"selectedCellsArray %#",selectedCellsArray);
cell.selectedBG.hidden=NO;
[cell setSelected:NO animated:YES];
}
else
{
cell.selectedBG.hidden=YES;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
#try{
// TODO: Select Item
if (shareEnabled) {
[selectedCellsArray removeAllObjects];
AVMThemeCell *collectionCell = (AVMThemeCell*)[tableView cellForRowAtIndexPath:indexPath];
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row];
if ( ![selectedCellsArray containsObject:[NSString stringWithFormat:#"%#",rowNsNum]] )
{
[selectedCellsArray addObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row]];
collectionCell.selectedBG.hidden = NO;
[collectionCell setSelected:NO animated:YES];
// NSLog(#"view is %#",collectionCell.selectedBG);
NSLog(#"selected view is hidden = %hhd",collectionCell.hidden);
NSLog(#"selected in didselect %d",(int)indexPath.row);
}
else {
[selectedCellsArray removeObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row]];
collectionCell.selectedBG.hidden = YES;
NSLog(#"DEselected in didDEselect");
}
}
} #catch (NSException *e){
NSLog(#"Exception! %#",e);
}
}
A more simple approach to do this is to use NSIndexPath.
Create NSIndexPath variable to track last selected cell.
#property (nonatomic, strong) NSIndexPath *selectedIndexPath;
Initialisation variable in viewDidLoad() method:
self.selectedIndexPath = [NSIndexPath indexPathForRow:-1 inSection:-1];
Observe value -1 for row and -1 for section in above line which will intialize indexPath with no row selection in tableView.
Now, UITableView datasource methods will be like below:
In cellForRowAtIndexPath method put a condition to check current indexPath is selected or not?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// . . .
// Change background color of selected cell
if (self.selectedIndexPath == indexPath) {
[cell setBackgroundColor:[UIColor orangeColor]];
} else {
[cell setBackgroundColor:[UIColor clearColor]];
}
// . . .
}
Update selected index path in didSelectRowAtIndexPath method:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// . . .
AVMThemeCell *previousCell = (AVMThemeCell *)[tableView cellForRowAtIndexPath:self.selectedIndexPath];
previousCell.backgroundColor = [UIColor clearColor];
self.selectedIndexPath = indexPath;
AVMThemeCell *selectedCell = AVMThemeCell *[tableView cellForRowAtIndexPath:self.selectedIndexPath];
selectedCell.backgroundColor = [UIColor orangeColor];
// . . .
}

UITableView checkmark imageview is set on multiple cellls

I have a table view that list currencies ... I would like that only one can be selected at one time (if the user clickes an already selected cell it should remain selected)... the check mark is an uiimageview...
Here is the code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.currencyList fetchedObjects] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CurrencyCell";
CurrencyCell *cell = (CurrencyCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Currency *currency = [self.currencyList objectAtIndexPath:indexPath];
cell.currencyName.text = currency.name;
cell.curencyAbreviation.text = currency.abreviation;
if ([currency.isDefault boolValue] == YES) {
cell.selectedCurrency.image = [UIImage imageNamed:#"Checkmark.png"];
checkedCell = indexPath;
NSLog(#"The default currency cellfor row is :%#",currency);
NSLog(#"the checkedcell index path is:%#",checkedCell);
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// [self.delegate theSelectedCurrencyIs:[self.currencyList objectAtIndexPath:indexPath]];
if (![indexPath isEqual:checkedCell]) {
CurrencyCell *cell = (CurrencyCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.selectedCurrency.image = [UIImage imageNamed:#"Checkmark.png"];
selectedCurrency = [self.currencyList objectAtIndexPath:indexPath];
NSLog(#"The selected currency is %#",selectedCurrency);
NSLog(#"The indexpath of the new selected currency is %#",indexPath);
CurrencyCell *previoslySelectedCell = (CurrencyCell *)[self.tableView cellForRowAtIndexPath:checkedCell];
NSLog(#"name of the previously selected cell %#",previoslySelectedCell.currencyName);
previoslySelectedCell.selectedCurrency.image = nil;
// [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,checkedCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView reloadData];
checkedCell = indexPath;
}
}
The problem is that the check-mark image is showing up in more than one selected cell.. the selected indexpath is ok... but a lot of cells look check-marked ... seems like a few on every scrolled screen
What would be the problem here?

Resources