cellForRowAtIndexPath inserting in array - iphone

I'm getting a weird issue. I have a custom UITableViewCell and each cell has a UIButton and UITextField. When the button is clicked, it changes the textfield value to some constant.
Now in the cellForRowAtIndexPath method I have this:
folderTitleTextView.tag=indexPath.row;
[arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row];
NSLog(#"indexpath.row:%i", indexPath.row);
NSLog(#"text fields count %i", [arrayOfTextFields count]);
So if I have two cells, then every time I reload the table, it adds two more objects to the arrayofTextFields, even though it should replace the existing ones. So if I have two cells and I reload the table 3 times, then for some reason arrayOfTextFields count is 8.

This folderTitleTextView.tag=indexPath.row; is not a good idea because everything starts with a tag of 0, so when accessing views with viewWithTag:0 or when setting up the row 0, you will get weird results.
I would suggest also checking the number of items in arrayOfTextFields and use [arrayOfTextFields replaceObjectAtIndex:indexPath.row withObject:folderTitleTextView]; or [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row]; depending on the current count for arrayOfTextFields
Try this:
folderTitleTextView.tag = (indexPath.row + 100);
if ([arrayOfTextFields count] <= indexPath.row) {
[arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row];
} else {
[arrayOfTextFields replaceObjectAtIndex:indexPath.row withObject:folderTitleTextView];
}
NSLog(#"indexpath.row:%i", indexPath.row);
NSLog(#"text fields count %i", [arrayOfTextFields count]);

The question is what are you trying to do?
Right now you add the textView to an array each time a cell is displayed.
If you have 1 cell you have 1 textView in the array because cellForRowAtIndexPath: was called 1 time.
If you add another cell so you have 2 total cell cellForRowAtIndexPath will be called another 2 times and it will add 2 textViews to the array that already has one -> 3
If you add another cell cellForRowAtIndexPath adds 3 more textViews to the 3 that are already there -> 6
So much for the explanation of your results.
My suggestion is to get rid of that array and get rid of the tag, most likely those are not needed at all.
you can access the cell with something like this:
- (IBAction)buttonPressed:(UIButton *)sender {
UIView *contentView = [sender superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
// you should assign a tag to the textField of your cell. Use the same tag for each textView in all cells.
UITextField *textField = (UITextField *)[cell viewWithTag:42];
textField.text = #"Foo";
}

Related

cell labels are not refreshing in table

I am attempting to call a reloadData on my table's rows on a viewDidAppear method access. However, my cells are not refreshing their values and I cannot figure out why, as it seems everything is being accessed in the order it is suppose to. To make matters more odd, 1 row actually does refresh, but none of the others do.
Here is my code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Set up the cell...
static NSString *CellWithIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
NSLog(#"generating cell contents");
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [_tableGroup.options objectAtIndex:rowcount];
rowcount++;
//label for currently selected/saved setting
_currentSetting = [[UILabel alloc] initWithFrame:CGRectMake(160, 8, 115, 25)];
[_currentSetting setFont:[UIFont systemFontOfSize:14]];
_currentSetting.backgroundColor = [UIColor clearColor];
_currentSetting.textColor = [UIColor blueColor];
_currentSetting.textAlignment = NSTextAlignmentRight;
[cell.contentView addSubview:_currentSetting];
NSLog(#"added new label to cell");
}
//depending on the setting, set the label in the cell to what is currently selected
if (indexPath.section == 1 && indexPath.row == 0) {
_currentSetting.text = [NSString stringWithFormat:#"%# %#",[settings.mapDistance stringValue], NSLocalizedString(#"MILES_IDENTIFIER", nil)];
NSLog(#"setting map distance label: %#", settings.mapDistance);
}
else if(indexPath.section == 1 && indexPath.row == 1)
{
_currentSetting.text = [NSString stringWithFormat:#"%# %#",[settings.maxCustomers stringValue], NSLocalizedString(#"ITEMS_IDENTIFIER", nil)];
NSLog(#"setting max customers: %#", settings.maxCustomers);
}
else if(indexPath.section == 2)
{
_currentSetting.text = [NSString stringWithFormat:#"%# %#",[settings.maxProducts stringValue], NSLocalizedString(#"ITEMS_IDENTIFIER", nil)];
NSLog(#"setting max products: %#", settings.maxProducts);
}
return cell;
}
based on this code, i get this output with my NSLOGS.
this is the first run of the cells when the view is created. It generates 4 cells, puts labels in each cell, and in 3 of those labels, puts in a value.
generating cell contents
added new label to cell
generating cell contents
added new label to cell
setting map distance: 15
generating cell contents
added new label to cell
setting max customers: 250
generating cell contents
added new label to cell
setting max products: 150
at this point i have clicked a row, went to a different screen, and have now returned. as you can see, map distance is different. although no change is displayed, even though the code to change the label's text is accessed during the reload process.
reloading data
generating cell contents
generating cell contents
setting map distance: 25
generating cell contents
setting max customers: 250
generating cell contents
setting max products: 150
again, I'm at a loss because the last row DOES refresh correctly. But none of the others do.
Thanks
When you reload your tableView, the cells already exist and are dequeued from the tableView, so the condition if (cell == nil) returns false, and the cell creation code is not executed.
In that cell creation code, you are assigning a value to _currentSetting and then proceed with the acode assuming that value is correct. However, when the cell creation code is not executed, that value points to the latest created cell, and thus, it won't update.
To fix this: make _currentSetting a local variable and change the code to look like this:
(You don't really need to make it a local variable, but it's more appropriate because you don't really need a reference to the last label you created after you leave this method)
UILabel *_currentSetting = nil;
if (cell == nil) {
_currentSetting = ...
_currentSetting.tag = 123;
}
else
_currentSetting = [cell.contentView viewWithTag:123];
...
The problem here is that the second time (when you are reloading the view ) the _currentSetting is not having a valid memory .So it is better to implement a custom cell and do the job
Better refer this an excellent guide
The second time around, you can see that "added new label to cell" isn't being called, so you're re-using an old tableViewCell.
Note that you're not setting _currentSetting when re-using a cell, only when creating a new cell. So _currentSetting is set to the last new cell that was created, most likely the last cell in the table.
You need to make sure to set _currentSetting to the correct label (maybe by using viewWithTag: or something similar).
(e:f;b)

Displaying a "No rows found" message in UITableView with Core Data

I have implemented an iPhone app that uses UITableViewController/UITableView and Core Data. Further, I use a NSFetchedResultsController to manage the table data. This was all very straight forward and works great. I then decided that I should display a message in the UITableView when no rows where found/retrieved. After researching this, it appeared that the best way (perhaps the only way) to do this was to return a "dummy" cell that contains the message. However, when I do this, I get a nastygram from the runtime system that complains (and rightfully so) about data inconsistencies: "Invalid update: invalid number of sections. The number of sections contained in the table view ...". Here is the relevant code:
- (NSInteger) numberOfSectionsInTableView: (UITableView *)tableView
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) return 1;
return [[self.fetchedResultsController sections] count];
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) return 1;
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex: section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *) tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) {
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = #"No widgets found.";
return cell;
}
STCellView *cell = (STCellView *)[tableView dequeueReusableCellWithIdentifier: #"ShieldCell"];
[self configureCell: cell atIndexPath: indexPath];
return cell;
}
I have read responses from similar questions and it appears that I should use
insertRowsAtIndexPaths: withRowAnimation:
to insert the "dummy" message row into my table. However, this also means removing the "dummy" row when a real row is inserted. I can do this, but it seems like there should be an easier way to accomplish this. All I want to do, is to display a message indicating that there are no rows in the table (simple enough?). So, my question is this: Is there a way to display a message in an UITableView without using the "dummy" cell approach OR is there a way to convince UITableViewController/NSFetchResulsController that this is only a "dummy" row and they should not get so upset about it because it is not a real row (from my point of view) in the table?
Any help you can provide would be very appreciated (I am a struggling newbie to iPhone development and I want to learn the best practices). Thanks.
Rather than hack with the tableview datasource to get the intended UI you should add the "No rows found" message to the tableview header instead.
I did as follows in viewDidLoad.
UILabel *label = [[UILabel alloc] init];
[label setTextColor:[UIColor lightGrayColor]];
[label setText:#"No widgets found."];
[label sizeToFit];
label.frame = CGRectMake((self.tableView.bounds.size.width - label.bounds.size.width) / 2.0f,
(self.tableView.rowHeight - label.bounds.size.height) / 2.0f,
label.bounds.size.width,
label.bounds.size.height);
[self.tableView insertSubview:label atIndex:0];
In this case, each TableViewCells must be opaque to hide the label. or need to toggle the hidden property of the label according to the row count.
An alternative approach, which I have used before is to use Core Data to manage the update for you by inserting a 'no rows' entity for the section where no rows have been detected in your model class, which handles the data update.
There are a number of ways to implement this e.g. set the name/title field to a known status message or a flag within the entity. Once inserted you can detect the 'no rows' entity in the cellForRowAtIndexPath delegate method and insert an alternative table cell to show the message.
Just remove the 'no rows' entity before refreshing the data for that section.
My simple suggestion to display an empty message is to rearrange your controller to be a simple UIViewController (not a UITableViewController).
This UIViewController is composed by a UITableView (the controller is the data source and the delegate for your table) and by a UILabel (or a UIView that contains a UILabel) that displays the empty row message.
In this manner you can control the visibility of the table and the label based on the retrieved rows.
This approach could be laborious but I think it's good to avoid hacking NSFetchResultsController and data source. Furthermore you could have a complete control on arranging the position for your empty message.
As #Rog suggested you could also use the table view header to display that message. As you prefer.
Hope it helps.

UITableView showing more rows than specified in numberOfRowsInSection:

I want my tableView to show 6 rows with text in it, in this case "Example." As far as I can tell, I have my numberOfSectionsInTableView: and numberOfRowsInSection: set properly. See example code below:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
// Return the number of rows in the section.
return 6;
}
- (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];
}
cell.textLabel.text = #"Example";
return cell;
}
The problem is when you see the image below showing lines for rows that shouldn't/don't exist.
How do I get rid of the lines showing past row 6?
The generally accepted way of doing this is to add a footer view with a frame size of CGRectZero, as such:
[tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]]
What this does is tell the table that there is a footer, and so it stops displaying separator lines. However, since the footer has a CGRectZero as its frame, nothing gets displayed, and so the visual effect is that the separators simply stop.
Swift Version
The easiest method is to set the tableFooterView property:
override func viewDidLoad() {
super.viewDidLoad()
// This will remove extra separators from tableview
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
}
This is Because of Your Table-view Height. Weather you have Write
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
// Return the number of rows in the section.
return 6;
}
But its show rows According to Table-view Size. If you Dont want to show This extra Lines then Make UITableView Style Plain To Grouped.
Short and simple answer..
self.tableView.tableFooterView = [UIView new];
You could do something along the lines of:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:7 inSection:0];
[self.mytableView cellForRowAtIndexPath:indexPath].hidden = YES;
Im sure there are some better ways but this is the first thing that came to mind.
If you're referring to the light gray lines that appear below the last row, that's simply the default way a UITableView draws the row separator.
You could try changing the Separator style in Interface Builder (see the images below) to see if one of those might be more to your liking.
You didn't say what you do want to see past the last row. If you just want to see the window background, then just embed your table view in a UIView that's just tall enough to show the number of rows you want to see. If you want to see more rows without scrolling, then you would have to adjust the size of that containing view based on the number of rows.
To programmatically remove it, use this:
[yourTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
It's a lot easier to:
return numberOfSections + 1
return 0 rows in the final section
This keeps it simple!

TableViewCell's textLabel value returns to 1 when cell is scrolled out of the view

i have a table view in which i can add 1 or subtract 1 to the value of my cell.textLabel.text but when i switch views and return or scroll a cell out of the view, and when it comes back into view, the textLabel's value returns to 1 which is the original starting point! Please help! Here is the code to add and subtract 1:
- (IBAction)addLabelText:(id)sender{
cell = (UITableViewCell*)[sender superview]; // <-- ADD THIS LINE
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text
intValue] +1];
}
- (IBAction)subtractLabelText:(id)sender
{
cell = (UITableViewCell *)[sender superview];
if ( [[cell.textLabel text] intValue] == 0){
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] +0];
}
else{
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] -1];
}
}
This is happening because, the cells will be re-used on scrolling. The table view's datasource method will be invoked, hence the values get reset to the original value. You can maintain an array of NSNumbers as a datasource to the tableview (is, in cellForRowAtIndexpath: , set the text fo the cell label from the array). Each time you need to add or subtract, do it the corresponding NSNumber obj and re-load the tableview.
Seems like you are allocating a new cell each time.. and not using the cell re-usablility method.
In your case, when you are performing arithmetic actions to your previous values and you don't have an array to store previous values. The easiest way to fix this is make your Cell-Identifier unique. (something like #"Cell-%d",indexPAth.row)
Note: However, more efficient way would be to save your result in the array you are populating your data from, without making you Cell-Identifier unique.
You are not updating your data modal. That is why it is taking the original content value.
After change the cell text value reload the tableview [self.tableview reloadData]

When an UITableView is empty, show an UIImage

This is related to another question of mine which wasn't answered in a helpful way (message when a UITableView is empty).
I'm trying to show an UIImage graphic that says You haven't saved any bookmarks over an UITableView when it's empty. I have NSNotification set-up so that when bookmarks are added or deleted, a message is sent so that the UITableView can be updated.
I've been trying to do it with this code. Why won't this work?
- (void)bookmarksChanged:(NSNotification*)notification
{
[self.tableView reloadData];
UIImageView* emptyBookmarks = [[UIImageView alloc] initWithFrame:CGRectMake(75, 100, 160, 57)];
emptyBookmarks.alpha = 1;
emptyBookmarks.image = [UIImage imageNamed:#"emptyBookmark.png"];
[self.view addSubview:emptyBookmarks];
[emptyBookmarks release];
if ([self.dataModel bookmarksCount] == 0)
{
emptyBookmarks.alpha = 1;
}
else
{
emptyBookmarks.alpha = 0;
}
}
I'm probably approaching this the wrong way... But if salvageable, what am I doing wrong?
When I initially have an empty bookmarks tableview, there's no image displayed. After I add a bookmark and then delete it, the image shows. Grrh.
Another way (and IMO the correct way) to do this is to manipulate the backgroundView property on the UITableView.
While making a single cell with a custom image cell would certainly works, I think it overly complicates the logic of your UITableViewController's data source. It feels like a kludge.
According to UITableView documentation:
A table view’s background view is automatically resized to match the
size of the table view. This view is placed as a subview of the table
view behind all cells , header views, and footer views.
Assigning an opaque view to this property obscures the background color
set on the table view itself.
While you probably don't want to just set it to your UIImageView, it is very easy to make a UIView that contains the UIImageView that you want.
Well first off if you were going to do it that way, you would need to reload the tableView after updating the image or model etc. and not before.
But you are probably making things more complicated than they need to be!
Why not just check to see if the data for section 0 and indexPath.row 0 are empty and if so in cellForRowAtIndexPath display a text message accordingly.
// First make sure there is always one row returned even if the dataModel is empty.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger numRows = 0;
if ([self.dataModel lastObject]) {
// Return the number of rows in the section.
numRows = [self.dataModel count]; // etc.
}
if (numRows < 1) numRows = 1;
return numRows;
}
// Then display the data if there is some, otherwise a message if empty.
-(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 ([self.dataModel lastObject]) {
// setup the cell the normal way here.
} else { // the datasource is empty - print a message
cell.textLabel.text = nil;
cell.detailTextLabel.text = NSLocalizedString(#"You haven't saved any bookmarks", #"");
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.7];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
Are you sure [self.dataModel bookmarksCount] is equal to 0 ?
While I agree that you are probably going about this the wrong way,
your image is allocated and added in your bookmark changed, your notification does not trigger when there are no bookmarks initially. Hence you don't see the image. Call the bookmar changed when your table view inits or appears.
Probably the best way to achieve this is to perform a check in your numberOfRowsInSection method to return 1 if your data source is empty. Then in cellForRowAtIndexPath check if your data source is empty and if it is, create a custom cell that contains whatever you want. In heightForRowAtIndexPath you need to return your custom cell height if your datasource is empty, but only if you want the cell larger than the default. At least that is how I would approach it.
when bookmarks count is nil add one to your row method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
int c;
c = bookmarks.count;
if(c == 0){
c = 1;
}
return c;
}
and then the same check again in your cellforrowatindexpath.
Another thing to be aware of in this situation is that if you're using core data and you're datasource is feeding off an entity, you will want to make sure your model matches. You can get some weird side-effect behavior in certain situations. This is especially true if you allow editing and core data has an empty model but you're tableview is still showing a cell.