Make Change in TableViewCell - ios

I'm working on the TableView, and I have used the label on the TableViewCell and on the button click I want to hide the label from all cells in my table,
In the label I have set the tag:
label.tag = indexPath.row+1;
And on the button click I am using the code like this:
for (int i = 0; i < Array.count; i++)
{
[[self.view viewWithTag:i+1] setHidden:YES];
}
But from my code the label is hiding only from the last cell not all the others.

You can simply do this with another way.
First you need to declare a BOOL in your class
#property(assign,nonatomic) BOOL hideLabels;
Next in your button action handler method, set this YES
In your cellForRowAtIndexPath, check whether hideLabels is YES, if yes, the hide labels using code.
cell.yourLabel.hidden = hideLabels;
Now reload the table after setting hideLabels as YES
[self.tableView reloadData];

for(id object in tableView.subviews)
{
if([object isKindOfClass:[UILabel class]])
{
UILabel *label = (UILabel *) object;
[[label setHidden:YES];
}
}

In your ViewController.h
BOOL isLabelHidden;
in ViewController.m
- (void)viewDidLoad
{
isLabelHidden = FALSE;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TableCell";
UILabel *lbl;
UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if(isLabelHidden)
[lbl setHidden:YES];
else
[lbl setHidden:NO];
}
in you button clicked method
- (void)buttonClicked
{
isLabelHidden = TRUE;
[tableView reloadData];
}

You should first get the reference to the UITableViewCell and then you can remove the labels in them.
First of all get the reference to all the cells in your tableview as follows:
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
And now iterate through those cells in cells Array to hide the label view,
for (int i = 0; i < cells.count; i++)
{
[[[cells objectAtIndex:i] viewWithTag:i+1] setHidden:YES];
}
Source:How can I loop through UITableView's cells?

Related

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.

How to create dynamic cell in tableview?

I am facing issue regarding Dynamic cell in UITableView. I want to create dynamic rows while user clicked on button in tableview.
E.g.: in mytableview there are two rows as following :
Car :+
Bike :+
When user clicked add button then I have to show two more rows below car cell same thing as while user clicked on in front of bike add button then I have to show two more cells.
I think you need to have 2 sections, a bike and a car section with two data arrays to manage content of all cells. You may need to have two types of cell, an "add" cell and a "standard" cell.
Here is an example:
-In your viewDidiLoad:
self.bikeArray = [NSMutableArray arrayWithArray:#[#"Add bike"]]; // Aray to fill section 0
self.carArray = [NSMutableArray arrayWithArray:#[#"Add car"]]; // Aray to fill section 1
self.typeOfVehicleArray = #[#"Bike", #"Car"];
self.dataArray = #[self.bikeArray, self.carArray];
To create two types of cell, check indexPath.row:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
switch (indexPath.row) {
case 0:{
NSString *addIdentifier = #"addIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:addIdentifier];
if (!cell){
// Add button...
CGFloat buttonWidth = 60.f;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addIdentifier];
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - buttonWidth - 10.f , 5.f, buttonWidth, cell.frame.size.height - 10.f)];
[b setTitle:#"ADD" forState:UIControlStateNormal];
// ...with a wonderful color
b.backgroundColor = [UIColor greenColor];
[b addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:b];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
break;
}
default:{
NSString *standardIdentifier = #"standardIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:standardIdentifier];
if (!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:standardIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
break;
}
}
NSArray *vehicleArray = self.dataArray[indexPath.section];
cell.textLabel.text = [vehicleArray objectAtIndex:indexPath.row];
return cell;
}
Don't forget number of cells / sections:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.dataArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *vehicleArray = self.dataArray[section];
return [vehicleArray count];
}
Then you can implement buttonPressed:
- (void) buttonPressed: (id)sender{
// Find the section
UIButton *b = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[b superview];
NSInteger section = [self.tableView indexPathForCell:cell].section;
// Get vehicle array (bikeArray or carArray)
NSMutableArray *vehicleArray = self.dataArray[section];
NSString *vehicleType = [self.typeOfVehicleArray objectAtIndex:section];
NSInteger nextVehicle = [vehicleArray count];
NSString *firstRowToAdd = [NSString stringWithFormat:#"%# %lu", vehicleType, (long)nextVehicle];
NSString *secondRowToAdd = [NSString stringWithFormat:#"%# %lu", vehicleType, (long)(nextVehicle + 1)];
// Add object in vehicle array
[vehicleArray addObject:firstRowToAdd];
[vehicleArray addObject:secondRowToAdd];
// Create array of corresponding indexPath and update tableview
NSArray *indexPathArray = #[[NSIndexPath indexPathForRow:nextVehicle inSection:section],
[NSIndexPath indexPathForRow:(nextVehicle + 1) inSection:section]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];
}
You can control number rows in UITableView's tableView:numberOfRowsInSection: function that is defined in UITableViewDataSource Protocol. Just define an integer variable that holds the number rows user should see. On every Add button click increase the value of variable.
#implementation ViewController {
int numberOfRows;
}
- (void)viewDidLoad {
[super viewDidLoad];
numberOfRows = 3;
}
-(IBAction) addButtonClicked
{
numberOfRows++;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return numberOfRows;
}

Strange behavior - Row won't reselect until three taps

I'm currently facing a strange issue with a UITableView in iOS whereby deselected rows are no longer selectable immediately, you must tap three times before you can select again. I'm implementing something akin to a checklist, with a "clear" button to go through and deselect all the cells. This effect only occurs when the cell had been previously selected, but the "clear" button is pressed. If a cell had been untouched before and is touched after the clear button, it will be presented and toggle fine.
Here is what I have
I should mention that the VC this Table is in is stored inside a container, hence the reference to it.
The deselect
- (IBAction)btnClearTapped:(id)sender {
UITableView *locationList = self.locationsVc.tableView;
for (NSUInteger i = 0; i < [locationList numberOfSections]; i++) {
for (NSUInteger j = 0; j < [locationList numberOfRowsInSection:i]; j++) {
[locationList deselectRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:i] animated:YES];
}
}
}
The didSelectRowAtIndexPath method
- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
BOOL isChecked = !((NSNumber *) cellToggleDict[indexPath]).boolValue;
cellToggleDict[indexPath] = #(isChecked);
UIView *selectionColorView = [[UIView alloc] init];
if (isChecked) {
selectionColorView.backgroundColor = selectedColor;
selectedLocations[indexPath] = [[Search sharedManager] locationAtIndexPath:indexPath];//PFObject
}
else {
selectionColorView.backgroundColor = unselectedColor;
[selectedLocations removeObjectForKey:indexPath];
}
cell.selectedBackgroundView = selectionColorView;
}
And finally the dequeue and redraw method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Reuse" forIndexPath:indexPath];
PFObject *object = [[Search sharedManager] locationAtIndexPath:indexPath];
cell.textLabel.text = object[#"Name"];
BOOL isChecked = ((NSNumber *) cellToggleDict[indexPath]).boolValue;
UIView *selectionColorView = [[UIView alloc] init];
if (isChecked) {
selectionColorView.backgroundColor = selectedColor;
}
else {
selectionColorView.backgroundColor = unselectedColor;
}
cell.selectedBackgroundView = selectionColorView;
return cell;
}
You don't clear the cellToggleDict entries in the btnClearTapped: method. You should have.
- (IBAction)btnClearTapped:(id)sender {
UITableView *locationList = self.locationsVc.tableView;
[cellToggleDict removeAllObjects]; // Clear all objects from the selected store
for (NSUInteger i = 0; i < [locationList numberOfSections]; i++) {
for (NSUInteger j = 0; j < [locationList numberOfRowsInSection:i]; j++) {
[locationList deselectRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:i] animated:YES];
}
}
}

Find indexPath of cell by label

I have table with cells; each cell contain label with phone number. When i tap on the label, UIMenuController appears.
Is there a main way to find indexPath of cell, which contain selected label? (didSelectRowAtIndexPath: should not be called)
I can imagine many dirty hacks, but i looking for a main/good solution.
upd
I have reference to selected label.
Edit:
This is a better way.
- (IBAction)someMethod:(id)sender {
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
}
From your label, search for the cell object in the label's hierarchy:
-(UITableViewCell*) cellContainingView:(UIView*)view
{
UIView* currentView = view;
while (currentView)
{
if ([currentView isKindOfClass:[UITableViewCell class]])
{
return (UITableViewCell*)currentView;
}
currentView = currentView.superview;
}
return nil;
}
Once you have the cell, call [tableView indexPathForCell:cell]
The use of this method instead of hard coding view.superview.superview makes your code stronger because it handle possible changes in cell's view hierarchy through system's versions.
You could go:
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
for (UITableViewCell *cell in cells){
for (UILabel *label in cell.subviews){
if (label == yourLabel)
indexPath = [tableView indexPathForCell: cell];
}
}

Cannot refresh cell textLabel in tableView

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;
}

Resources