Text in UITableViewCell missing when scroll down - iphone

I added several cells to a tableview and each cell has a textField in the right to let users input texts. I find that when I scroll down and go back, the input of the first few lines will disappear. Does anybody know what's the problem?
The following is a piece of my codes:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
//init cell
static NSString *TableIdentifier = #"MyIdentifier";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:TableIdentifier] autorelease];
}
//set cell for each row
if([indexPath row] == 0)
{
cell.textLabel.text = #"Row A";
txt_A = [self CreateTextField]; //create textField
[cell.contentView addSubview:txt_A]; //add textField to cell
}
else if([indexPath row] == 1)
{
cell.textLabel.text = #"Row B";
txt_B = [self CreateTextField];
[cell.contentView addSubview:txt_B];
}
else{...} }

You mean the user input will disappear? If so this is probably because cellForRowAtIndexPath: reuses the cell and will execute the [self CreateTextField] again.
So, unless you store the user input before the cell disappears, your cells will be redrawn empty and reinitialized empty.
If you do store the user input, you could reinitialize the cell with the right user input.

I believe that when a cell leaves the screen (due to scrolling) the iPhone immediately releases it to save memory (thus loosing the user input). Now when you scroll back up, it creates a new cell with a new UITextField in the old position with
[self CreateTextField];
You have to store the user input for each text field separately. For example, you could become the text field's delegate and catch
- (BOOL)resignFirstResponder
to be notified when the user leaves the text field focus. At this point you can assume that the user is finished with this particular field and store it.

You can use method to save user inputs:
- (void)textFieldDidEndEditing:(UITextField *)textField
This methods called then user end editing the field. Save user inputs to array, for example.

Related

UITableViewCell background disappears?

The UITableViewController in my app pulls data from a json data source. I have also created a custom UITableViewCell background using CG. There is a very interesting bug that happens and I have no idea why. I will walk you through what happens and how I recreate it:
Tap to enter table view.
Without scrolling the table at all I immediately tap on an item in view.
After tapping on that item I press the back button to return to the table view.
If I then scroll down the first cell to appear from off screen will not have my custom back ground. It will just be the default for a cell. Then if I continue to scroll down every 10th cell will have the same issue.
This bug only occurs in this exact process. If I were to scroll the table view at all before tapping on an item it would not happen.
Here is the relevant code for the tableview controller:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Will remove all of the used codes from the table if setting is enabled
if (self.shouldHideCodes) {
NSMutableArray *tempArray = [self.jsonCodeData mutableCopy];
[tempArray removeObjectsInArray:[self.usedCodes usedCodes]];
self.jsonCodeData = tempArray;
}
return [self.jsonCodeData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (self.jsonCodeData) {
cell = [tableView dequeueReusableCellWithIdentifier:#"code cell"];
if ([cell isKindOfClass:[CodeCellTVC class]]) {
CodeCellTVC *tvcCell = (CodeCellTVC *)cell;
if (![tvcCell.backgroundView isKindOfClass:[CustomCellBackground class]]) {
tvcCell.backgroundView = [[CustomCellBackground alloc] init];
}
NSDictionary *codeDict = [self.jsonCodeData objectAtIndex:indexPath.row];
// Retrieve code string from dictionary
NSString *codeText = [NSString stringWithFormat:#"%#", [codeDict objectForKey:#"code"]];
tvcCell.codeTableLabel.text = codeText;
}
}
return cell;
}
The thing that confuses me is how it reacts. That when the bug happens every 10th cell has the issue and not every one. I don't have anything outside of these method's that deal with the tableviewcell itself.
I understood your problem, you did a wrong at the time of initializing the cell,Every time your intializing the cell, so that every time memory will allocate for that cell, it will create memory issue.
Edit the code like bellow it will work for you.
cell = [tableView dequeueReusableCellWithIdentifier:#"code cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"code cell"];
}

UITableView Cell Button mixed up

I have a problem, setting a button to a UITableviewCell.
After viewDidLoad, the button is on the right place. But when I am scrolling down, the button is anyplace else.
Here is my code, I hope you can help me.
Thanks In Advance.
- (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.section == 0 && indexPath.row == 0 && _isAddImageViewLoad == NO) {
// Add Image Button
UIButton *addImage = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage* image = [UIImage imageNamed:#"AddImage#2x"];
addImage.frame = CGRectMake(110.0f, 10.0f, 110.0f, 110.0f);
[addImage setImage:image forState:UIControlStateNormal];
[cell.contentView addSubview:addImage];
_isAddImageViewLoad = YES;
} else {
NSDictionary *dictionary = [_items objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"data"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}
return cell;
}
It is because you are reusing the cells, and the button is getting placed when it shouldn't an easy solution in your else section. Write addImage.hidden = YES; and in your if statement put addImage.hidden = NO;
Just a couple things. If you use "AddImage" it will use the "AddImage#2x" automatically if it's a retina display. I don't think that will solve your issue but it could be causing weirdness.
When a table view cell is scrolled off the view it is "recycled" in a sense. It appears like you are using a bool to exclude the original cell from being loaded again with a button. You may want to use a header to hold your button if you always want it at the "top". You may also want to verify that the button is being removed when the cell is reused. if its not it will show up in the next row that reuses that cell.
On a side note... Buttons don't usually work very well in table view cells because they handle touches in very different ways. It's quite a bit of modification to get them to feel natural but that's another matter.
Hope that helps!
The problem is because of cell reuse. You need to put some code in the else clause to delete the button if it exits. One way to do this, would be to give your button a tag, like:
addImage.tag = 10;
Then in your else clause:
}else{
if (cell viewWithTag:10) [[cell viewWithTag: 10] removeFromSuperview];
...
The problem is because of the dequeue for the cells. The first time the tableview creates the cells, all the cells run through the
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
code. But when the section 0 row 0 is moved off the screen, that cell is pushed into the cell reusable queue.
Now when your tableview needs to display section 0 row 0, it will get a cell from the reuse queue. you will not get the same cell as the first time. So now you might have 2 cells with the button.
What you should do is have different CellIdentifier for section 0 row 0 , and all other sections and rows. Also create the button when creating the cell. So after the first time the tableView creates the cell, you will not be creating the the button everything.
Look at this line of code:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
This line of code means the UITableViewCells are not created every time. They are re-used as you scroll up and down. Using the code you have above, the UIButton will be created in the correct spot, but then as the cells are re-used, it will create the button in random spots.
One quick way to solve the problem, change the above line of code to simply
UITableViewCell *cell;

Modify existing reusable cells with cellForRowAtIndexPath: method

I use tableview with reusable cells. On each cell I have a textField with text, which I can modify. If text is empty, I delete that cell.
Lets say that we had 100 rows and we want to modify row number 1: we tap on it, give an empty string #"", scroll down to position number 50 and tap on this cell.
What now is going is that we detect tap gesture on another cell and I call method textFieldDidEndEditing: to see should I remove this cell from tableview. I use cellForRowAtIndexPath: to get the modified cell.
The problem is that there appear other cells with empty textField. I delete modified cell, but only one. I think that this is a problem with reusable cells.
Can anybody can help me with this problem?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ImageIdentyfier = #"StandardCellWithImageIdentifier";
StandardCellWithImage *cellImage = (StandardCellWithImage *)[tableView dequeueReusableCellWithIdentifier:ImageIdentyfier];
if(cellImage == nil) {
cellImage = [[StandardCellWithImage alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageIdentyfier];
}
cellImage.nameLabel.delegate = self;
Item *item = [self.mutableFetchResults objectAtIndex:indexPath.row];
cellImage.nameLabel.text = item.itemText;
cellImage.infoLabel.text = item.itemInfo;
cellImage.checkbox.userInteractionEnabled = YES;
cellImage.nameLabel.userInteractionEnabled = NO;
if(item.itemIsChecked.boolValue == YES) {
cellImage.checkbox.tag = indexPath.row;
[cellImage.tapGesture addTarget:self action:#selector(didSelectedImageAtIndexPath:)];
cellImage.checkbox.image = [UIImage imageNamed:#"checkbox-checked.png"];
} else {
cellImage.checkbox.tag = indexPath.row;
[cellImage.tapGesture addTarget:self action:#selector(didSelectedImageAtIndexPath:)];
cellImage.checkbox.image = [UIImage imageNamed:#"open-checkbox.png"];
}
return cellImage;
}
When you scroll from row 1 to row 50, already existing cells are reused - including your cell with empty textField. That is why you see it several times and why your delete routine removed only one instead of all.
Sounds like your cell creation at cellForRowAtIndexPath method needs fixing to make sure empty textfield is not automatically copied to recycled cells. Without seeing any code, this exercise is left to you.
Looked at code, thanx. Could not see any "easy" fix, so proposing that you should avoid the problem. So instead of checking cell taps, maybe you should check list scrolling.
The problem you have exists only because cell, which was being edited, was recycled due user scrolling the list. Therefore remove the problem by a) don't let user to scroll while editing text or b) stop text edit when user starts scrolling.
when your textFieldDidEndEditing is invoked finish , you should check whether the text is "" if it is "" I think you should delete it from the dataSource and then reloadData
your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method should write like this :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
XXXXXXXCell *cell = [tableView dequeueReusableCellWithIdentifier: kIdentifier];
if (cell == nil) {
//Init cell, only init
}
//Setup the cells detail, such as the textField.text and so on
return cell;
}

How to switch to a different view by clicking on the detailtextlabel in iPhone?

I have a table view in which I have 3 rows. First row is to select whether the clock should be in analog or digital fashion. Second row has a toggle switch which when switched on show the weather. Third row shows the timeformat i.e whether the user wants to select time in 24 hour format or 12 format.
The second row has been done. But I am confused on how to do with the first one i.e by default in the detailtextlabel of the first row digital should be displayed and when i click on the cell the text should change from digital to analog.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if(indexPath.row == 0){
if([cell.textLabel.text isEqualToString:#"Analog"]){
cell.textLabel.text = #"Digital";
}
else{
cell.textLabel.text = #"Analog";
}
}
}
Replace cell.textLabel.text by lbl.text if you are using any another label for displaying these values.
So you want to update the UITableView's first cell detailTextLabel, after the user clicks on it, right?
Well in the TableView delegate method, get a refference to the cell the user clicked on and modify it's detailTextLabel....
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.text = #"New Text";
}
Just make sure to check which cell the user clicked on before you change the text, since you have 3 cells...
Either check the cell row, or the cell existing text

My UITable is re-using cells when it shouldn't!

I have a UITableViewController which has two sections. The first section shows a single cell with centered text, saying Add a new Slide. The second section show the current slides.
When a user taps on the Add a new slide cell, a new UITableVeiwController is pushed onto the stack that shows an editor. If the user saves the new slide (by tapping save), the cell is added to the data source and the editor is popped from the stack.
I have two problems:
When the editor is popped, if a cell was deleted before Add a new slide was tapped, the old cell shows up instead of the new one. Popping the UITableViewController (by tapping the automatically generated back button) fixes this, but I'd like this to not happen at all. (Originally, popping the table did not update after popping the editor, so I added [self.tableView reloadData]; to the viewDidAppear method.)
After a certain number of slides, the last slide on the list becomes the Add a new slide cell. I know that the data is being entered properly because another part of the app, which uses the same data source, updates correctly. The table supports editing in the second section, and when you swap the order of the cells, it behaves correctly behind the scenes, but the wrong cell is still there.
What could be going on?
Here's some of my code:
Note that as I was gearing to post my code, I noticed a mismatch of the braces. The check for cell==nil seems to encompass the second part of the code which determines the content of the cells. This fixes the label of the cells in the second section of the table, but the style is still wrong. I've since fixed the code, but the original is posted here.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
if ([indexPath section] == 0 ) {
cell = [[[MBTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}else if([indexPath section] == 1){
cell = [[[MBTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
if ([indexPath section] == 0) {
[cell.textLabel setTextAlignment:UITextAlignmentCenter];
[cell.textLabel setText:#"Add a New Slide"];
}else if([indexPath section] == 1){
NSArray *storedViewsInfo = [[NSArray alloc] initWithArray:[kSettings arrayForKey:#"views"]];
if ([[[storedViewsInfo objectAtIndex:[indexPath row]] valueForKey:#"type"] isEqualToString:#"announcement"]) {
[cell.detailTextLabel setText:#"Custom Announcement"];
[cell.textLabel setText:[[[storedViewsInfo objectAtIndex:[indexPath row]] valueForKey:#"info"] valueForKey:#"text"]];
}
[storedViewsInfo release];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
}
return cell;
}
Without seeing the code, first thing that comes to mind is checking if you've given your custom cells different identifiers in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; method?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier1 = #"CellIdentifier1";
static NSString *Cellidentifier2 = #"CellIdentifier2";
if (indexPath.section == kAddSlideSection) {
CustomCell *cellType1 = (CustomCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
...
} else {
CustomCell *cellType2 = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
...
}
}
Also it might be worth considering implementing a delegate method that gets called when your user finishes adding the new slide - i.e. if successful call [self.tableview reloadData] from that method instead of in viewWillAppear.