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];
// . . .
}
Related
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.
I have a tableview in which i have provided checkmarks as a accessory to multiple cells.
Now I want to get values of all those cells having checkmarks.
#import "HealthIssues.h"
#interface HealthIssues ()<UITableViewDataSource,UITableViewDelegate>
{
NSIndexPath* checkedIndexPath;
}
#property (nonatomic, retain) NSIndexPath* checkedIndexPath;
#end
#implementation HealthIssues
#synthesize HealthIssuesTV;
#synthesize checkedIndexPath;
- (void)viewDidLoad {
[super viewDidLoad];
PickerList=[[NSArray alloc]initWithObjects:#"None" ,#"Diabetes", #"Heart Problem" , #"Thyroid" , #"Over Weight" , #"Kidney Issues" , #"Lever Issues" , #"Vitamins Deficiency" , #"Blood Pressure" , nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [PickerList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==Nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
if (indexPath.row == 0){
if ([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
cell.textLabel.text = [PickerList objectAtIndex:indexPath.row];
cell.tintColor=[UIColor blueColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
{
int z=0;
if (indexPath.row==0)
{
NSArray *visibleCells = [tableView visibleCells];
for (UITableViewCell *cell in visibleCells)
{
if (z==0)
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
z++;
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
z++;
}
}
}
else
{
if ([selectedCell accessoryType] == UITableViewCellAccessoryNone)
{
[selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[selectedCell setAccessoryType:UITableViewCellAccessoryNone];
}
[tableView reloadData];
}
}
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#end
This Works perfect for me as per my requirements. now i want to store selected rows in dictionary.
#interface selectUsers ()
{
NSMutableArray *selected_ids;
}
- (void)viewDidLoad {
[super viewDidLoad];
selected_ids = [[NSMutableArray alloc]init];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *_id = [[yourarray objectAtIndex:indexPath.row]valueForKey:#"_id"];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
[selected_ids removeObject:_id];
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
[selected_ids addObject:_id];
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}
}
Use selected_ids array where you want.
Try to get values from your data source of array and get all selected rows of UITableView:
Following code will give you all indexpaths of selected rows:
NSArray *arrIndexpaths = [YourTableView indexPathsForSelectedRows]; // Returns indexpaths for multiple selection in Table view.
Then Get value from the array by indexpath.row and indexpath.section whatever you used during in data source method.
First of all, you should do:
tableView.allowsMultipleSelection = YES;
Then you can get list of selected rows by:
NSArray *selectedIndexPaths = [self.tableView indexPathsForSelectedRows];
As you have now list of selected rows, you can get row or data of row.
You can use array for this.
- (void)viewDidLoad
{
arrData=[[NSMutableArray alloc]init];
}
On didSelectRowAtIndexPath add your value into array.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[arrData addObject:[YourDataArray objectAtIndex:indexPath.row]];
}
May be it will help you.
try this..
NSMutableArray *selectedIndexes ; // instance variable, do initialization in viewDidLoad
i am assuming that you are using didSelectRowAtIndexPath for selecting cell (i mean not a custom button action)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
{
if ([selectedIndexes containsObject:indexPath])
{
[selectedIndexes removeObject:indexPath];
}
else
{
[selectedIndexes addObject:indexPath];
}
}
Now you can get all selected cells using index values in selectedIndexes array
for ex UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:1];
edit :
remove all objects from selectedIndexes after selection process is over
#interface RestTableViewController ()<UISearchBarDelegate>{
NSMutableSet *setTemp;
// NSMutableArray *setTemp;
}
In ViewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
setTemp = [[NSMutableSet alloc] initWithCapacity:1];
. . .
}
In cellForRowAtIndexPath
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self markCell:cell atIndex:indexPath.row];
Create a Method
- (void)markCell:(UITableViewCell *)cell atIndex:(NSInteger)index{
if ([setTemp containsObject:[NSNumber numberWithInteger:index]]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
In didSelectRowAtIndexPath
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
{
// Restaurent is my Object File
Restaurent *obj = [restMutableArray objectAtIndex:indexPath.row];
if ([setTemp containsObject:[NSNumber numberWithInteger:indexPath.row]]) {
[setTemp removeObject:[NSNumber numberWithInteger:indexPath.row]];
// tempMainArray is an array which manages the title of selected or deselected Rows . . .
[tempMainArray removeObject:obj.strTitle];
NSLog(#"Selected Row Data %#",tempMainArray);
}
else {
[setTemp addObject:[NSNumber numberWithInteger:indexPath.row]];
[tempMainArray addObject:obj.strTitle];
NSLog(#"Selected Row Data %#",tempMainArray);
}
[self markCell:cell atIndex:indexPath.row];
}
To Select All The Cell
#pragma mark : Select All Data Method. . .
- (IBAction)actionBtnClicked:(id)sender {
{
[setTemp removeAllObjects];
for (int i = 0 ; i < [restMutableArray count]; i++) {
Restaurent *obj = [restMutableArray objectAtIndex:i];
[tempMainArray addObject:obj.strTitle];
[setTemp addObject:#(i)];
}
NSLog(#"%#",tempMainArray);
[self.tableView reloadData];
}
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];
}
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
I have a table view and 2 custom cells inside it. I want to use a (X) symbol i.e. the cross symbol and the tick symbol. I know for tick we have UITableViewCellAccessoryCheckmark but what to do for the (X) symbol. Can we have any custom accessory for this or else how to achieve this?
My code:
#pragma mark - Table View Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
optionsLabelArray = [[NSArray alloc] initWithObjects:#"Yes", #"No", nil];
static NSString *CellIdentifier = #"CheckerCell";
CustomCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.optionLabel.text = [optionsLabelArray objectAtIndex:indexPath.row];
cell.optionLabelSubtitle.text = [optionsLabelSubtitleArray objectAtIndex:indexPath.row];
if(indexPath.row == 0)
{
cell.textLabel.textColor = [UIColor colorWithRed:78/255.0 green:157/255.0 blue:19/255.0 alpha:1.0];
}
else if(indexPath.row == 1)
{
cell.textLabel.textColor = [UIColor colorWithRed:167/255.0 green:19/255.0 blue:43/255.0 alpha:1.0];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView ==_optionsTableView1) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
previousSelectedCell1.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryType=UITableViewCellAccessoryCheckmark;
previousSelectedCell1 = cell;
NSLog(#"Row : %ld", (long)indexPath.row);
if(indexPath.row == 0)
{
self.weatherSafeToPlay = YES;
}
else
{
// MatchDayDataController *sharedController = [MatchDayDataController sharedDataController];
// sharedController.actions = [sharedController.actions stringByAppendingString:#"Check Weather. "];
//[sharedController.actions appendString:#"Check Weather. "];
self.weatherSafeToPlay = NO;
}
NSLog(#"Is Weather safe: %hhd", self.weatherSafeToPlay);
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
not heard of any accessory type for cross but in such cases, i simply use unicode characters.
It's lighter than using an image and is a simple matter of just changing the text.
#"\u2713" for ✓
#"\u2717" for ✗
You can:
Create a custom UITableViewCell having a 32by32 (or any dimension) UILabel (on the right/left/middle/wherever)
in -didSelectRowAtIndexPath, you can change the text of this UILabel
#"\u2713" for checkmark or #"\u2717" for crossmark
A simple example (on the default UITableViewCell's default textLabel, just for the idea):
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if([cell.textLabel.text isEqualToString:#"\u2713"]) {
cell.textLabel.text = #"\u2717";
}
else {
cell.textLabel.text = #"\u2713";
}
}
OR... when not using a custom cell, something like:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
//set your text to cell.textLabel.text
//create your own UILabel
UILabel *lblAcc = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
[lblAcc setTag:100];
[lblAcc setText:#"?"];
[lblAcc setBackgroundColor:[UIColor redColor]];
[lblAcc setTextAlignment:NSTextAlignmentCenter];
//set as custom AccessoryView on cell
[cell setAccessoryView:lblAcc];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *strAccessory = [(UILabel *) [cell viewWithTag:100] text];
//the -isEqualToString is a bit heavier than checking a simple bool or int value
//so since you should be remembering the selected cells anyways, you can change
//the if-logic to compare with a bool rather than the string comparison.
//but for now, we'll do:
if([strAccessory isEqualToString:#"\u2713"]) {
[(UILabel *) [cell viewWithTag:100] setText:#"\u2717"];
}
else {
[(UILabel *) [cell viewWithTag:100] setText:#"\u2713"];
}
}
for more unicode characters... this link:
http://en.wikibooks.org/wiki/Unicode/List_of_useful_symbols
You can assign your own image to accessoryView of table cell. Create an image of (X) symbol and use that image as accessoryView.
cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"Your X Image"]];