I have a simple tableView with 20 rows. I created a subclass custom UITableview cell, and in cellforRowAtIndex, I add a textfield to the cell once every other 3 rows. When I scroll up and down text fields show up in the wrong rows. Note, I can't make UItextfield part of my custom cell, because this can be anything, checkbox, radio button, but for simplicity I chose UITextfield... What am I doing wrong?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TestCellIdentifier";
testCell *cell = (testCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(!cell)
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
else{
//HMMM I also tried removing it before adding it- it doesn't work neither
for(UIView *v in cell.subviews){
if(v.tag == 999 ){
[v removeFromSuperview];
}
}
//add UItextField to row if it's divisible by 3
if(indexPath.row %3 ==0){
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(400, 10, 300, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = [NSString stringWithFormat:#"%d",indexPath.row];
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.tag = 999;
[cell addSubview:textField];
}
}
cell.textLabel.text = [NSString stringWithFormat:#"%d",indexPath.row];
return cell;
}
don't use the Reusability ?
in this scene,i will not use the reusability
Reusing cells is a good thing and you should be able to do it.
You could consider removing the text field from the cell when it goes offscreen, before it is queued for reuse, in the delegate protocol method:
– tableView:didEndDisplayingCell:forRowAtIndexPath:
Knowing the row number you would know whether or not to remove the textfield.
Edited to add explanation:
On first glance your code looks OK, so I did a little test project.
The problem with your original code is that you're adding the textfield to the wrong "view" -- UITableViewCells have some structure that you need to pay attention to. Look at the documentation for the UITableViewCell contentView property. It says, in part:
If you want to customize cells by simply adding additional views, you
should add them to the content view so they will be positioned
appropriately as the cell transitions into and out of editing mode.
So the code should add to and enumerate subviews of the cell's contentView:
for(UIView *v in cell.contentView.subviews){
if(v.tag == 999 ){
[v removeFromSuperview];
}
}
...
textField.tag = 999;
[cell.contentView addSubview:textField];
Related
I am using UITableview cell for listing a set of questions and 2 textfield is for score 1 and score 2 i inputed the score and total showed on a label after that when am scrolling time the inputed data is disappear on the UITableview .Some one please help me to solve this issue and am adding these textfield and label on the view and this view is the subview of cell.contentview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
else{
for (UIView* view in cell.contentView.subviews) {
if ([view isKindOfClass:[UIView class]]) {
[view removeFromSuperview];
}
}
}
text field added as
UIView * vwbackground = [[UIView alloc] init];
[vwbackground setFrame: CGRectMake(5.0, 5.0, [UIScreen mainScreen].bounds.size.width-10, 90)];
vwbackground.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:vwbackground];
self.txtfldInPut1.clearButtonMode = UITextFieldViewModeWhileEditing;
self.txtfldInPut1.autocorrectionType = UITextAutocorrectionTypeNo;
self.txtfldInPut1.inputAccessoryView = numberToolbar;
[vwbackground addSubview:self.txtfldInPut1];
This is because data in table cell is keep on changing as per list items when scrolls . This is a feature of cells in table view .
what you need to do is at the time when put enter your score just update that value to the array/dictonary(whatever you have taken) from which you are intially showing your data in the list.
Hope it helps :)
CoreData returns BOOL value and according to the value I draw a UILabel on UITableViewCell accessoryView. The problem is that UILabel repeats itself also on the cells it shouldn't appear at all.
CGRect lblRect = CGRectMake(230, 7, 20, 20);
UILabel *lblEnabled = [[UILabel alloc] initWithFrame:lblRect];
lblEnabled.textColor=[UIColor whiteColor];
lblEnabled.textAlignment=NSTextAlignmentCenter;
[lblEnabled setFont:[UIFont fontWithName:#"Verdana" size:10.0]];
[lblEnabled setText:#"40"];
lblEnabled.backgroundColor= [UIColor colorWithPatternImage:[UIImage imageNamed:#"greenBg"]];
lblEnabled.layer.cornerRadius = 9.0;
lblEnabled.layer.masksToBounds = YES;
lblEnabled.tag = indexPath.row;
cell.accessoryView = lblEnabled;
[cell.contentView addSubview:lblEnabled];
So it appears sometimes on the cell where the BOOL value = NO; Your help is strongly appreciated.
EDIT: I draw these labels in cellForRowForIndexPath.
EDIT: I use storyboards, so I don't check if cell is nil.
-(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];
tableView.rowHeight=57.0;
}*/
Coin *coin=[[self frcFromTV:tableView ] objectAtIndexPath:indexPath];
cell.textLabel.text=coin.coinNominal;
if(coin.comSubject.length>0)
{
cell.detailTextLabel.text=[NSString stringWithFormat:#"%#%# (%#) | %#",[self returnCatalogDefinition:coin.catalogIndex],coin.kmRef, coin.dates, coin.comSubject];
}
else
{
cell.detailTextLabel.text=[NSString stringWithFormat:#"%#%# | %#",[self returnCatalogDefinition:coin.catalogIndex],coin.kmRef,coin.dates];
}
if(coin.isCommemorative.boolValue)
{
// implement label
}
if(coin.listed.boolValue)
{
CGRect lblRect = CGRectMake(230, 7, 20, 20);
UILabel *lblEnabled = [[UILabel alloc] initWithFrame:lblRect];
lblEnabled.textColor=[UIColor whiteColor];
lblEnabled.textAlignment=NSTextAlignmentCenter;
[lblEnabled setFont:[UIFont fontWithName:#"Verdana" size:10.0]];
[lblEnabled setText:#"40"];
lblEnabled.backgroundColor= [UIColor colorWithPatternImage:[UIImage imageNamed:#"greenBg"]];
lblEnabled.layer.cornerRadius = 9.0;
lblEnabled.layer.masksToBounds = YES;
lblEnabled.tag = indexPath.row;
cell.accessoryView = lblEnabled;
[cell.contentView addSubview:lblEnabled];
}
return cell;
}
In code below you probably add your label but because those cells are reusable you should handle else statement (hiding label or whatever is appropriate)
if(coin.isCommemorative.boolValue)
{
// implement label
//remove from that part of the statement this line:
//[cell.contentView addSubview:lblEnabled];
} else {
cell.accessoryView = nil;
//hiding or modifying label for other cases
}
if you will not deal with that else statement the change you made in if will be applicable to more than one cell because of the reusing mechanism
As a "side advice" I would recommend you to subclass UITableViewCell and add the property you want (label) to encapsulate that and make only public method for showing or hiding that accessor.
EDIT:
if your flag for a change is not specifying to which cell it has to indicate (for example using indexPath) then the result is as your one.
This is quite global state if(coin.isCommemorative.boolValue) not indicating to which cell it counts try for example (for just learning purpose) add if(coin.isCommemorative.boolValue && indexPath.row%2==0) and see the result.
Are you reusing cells? If so, then you need to remove that cell from contentView inside prepareForReuse method.
I have a table view with three table view cells.
During cell configuration, I add a UITextField to each of the cells and I also set the placeholder value on all of the text fields.
When the table view loads the end results looks like this:
The issue I'm having, is that when I scroll any of the cells "off the screen" when they reappear the placeholder text get darker and darker, like here:
When I then attempt to change the UITextField string value by typing a name in, or by programatically changing the placeholder value on the last cell, the old value of those properties stays, and the new value gets overlaid in the cell, like this:
Here are the methods responsible for configuring those cells:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
[self configureCell:cell forIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
for (UIView *subview in cell.contentView.subviews) {
[subview removeFromSuperview];
}
cell.backgroundColor = [UIColor whiteColor];
cell.autoresizesSubviews = YES;
cell.clearsContextBeforeDrawing = YES;
CGRect textFieldFrame = cell.bounds;
textFieldFrame.origin.x += 10;
textFieldFrame.size.width -= 10;
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame];
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor lightGrayColor];
textField.enabled = YES;
textField.userInteractionEnabled = NO;
textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
textField.clearsContextBeforeDrawing = YES;
textField.clearsOnBeginEditing = YES;
if (indexPath.section == ATTAddNewTimerSectionName) {
textField.placeholder = #"Name";
textField.userInteractionEnabled = YES;
textField.delegate = self;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
} else if (indexPath.section == ATTAddNewTimerSectionDate) {
textField.placeholder = #"Date/Time";
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else if (indexPath.section == ATTAddNewTimerSectionCalendar) {
if (self.userCalendarEvent == nil) {
textField.placeholder = #"See list of calendar events";
} else {
textField.placeholder = nil;
textField.placeholder = self.userCalendarEvent.title;
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
[cell addSubview:textField];
}
As you can see, I have tried various things, like removing all the subviews before adding a new view to the cell or setting -[UIView setClearsContextBeforeDrawing:YES] on both the cell and the UITextView and even setting the placeholder value to nil without success.
Any pointers would be much appreciated!
You are making a classic error that so many people make. Cells get reused as a table is scrolled.
As written, your code keeps creating and adding a new text field every time the cell is used. So you are seeing the result of having multiple text fields in a cell.
You want to only add one text field to a cell. Update your code so it only adds the text field if it isn't there already.
It seems you have a logic problem in the code. You add the text field directly to the cell but you try to remove it from the cell's contentView.
Change this:
[cell addSubview:textField];
to:
[cell.contentView addSubview:textField];
I have a master detail app in ios, with SDK 7.0, Xcode 5, using ARC.
master has many items, detail has a table view. When I click on an item, the contents of tableview will change. This works well until I put a UITextField in each cell, because I want to edit the contents in the table.
The problem is: when I click on a new item, the old contents don't disappear,so the contents of a cell is a superposition of the new UITextField's text and the old UITextField's text.
The first normal tableview like this:
After I click on an new item, the tableview will like this:
The snippet of codes of master is:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
LHBPoetry *poetry = poetryArray[indexPath.row];
self.detailViewController.poetryId = poetry.poetryId;
}
I have tried a lot of things in the above method, for example, I make all instances of the detail view controller to be nil; table view's data array removeAllObejects; table view reloadData; It can't fix the problem.
The snippet of detail is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"detailCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
UITextField *textField = textField = [[UITextField alloc] initWithFrame:
CGRectMake(90, 12, 200, 25)];
textField.tag = indexPath.row;
textField.text =_sentenceArray[indexPath.row];
textField.clearsOnBeginEditing = NO;
textField.delegate = self;
textField.returnKeyType = UIReturnKeyDone;
[textField addTarget:self
action:#selector(textFieldDone:)
forControlEvents:UIControlEventEditingDidEnd];
[cell.contentView addSubview:textField];
textField.text = _sentenceArray[indexPath.row];
return cell;
}
I draw this tableview in Main.storyborad, It has a prototype cell with an identifier.
Any help will be appreciated.
k there is something i want to tell, wy because u are keep on adding the textfields for reused cells, there is not one textfield in the cell ..:) there are more then one text field's, because of that u are getting overlapped with one other, i think u are using default "master- detail" application, and modifying it..:)
oky for that u need to modify like below
in master controller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(2, 3, 300, 30)];
[textField addTarget:self action:#selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEnd]; //hear u are adding once initially
textField.tag = 100;
[cell addSubview:textField];
}
NSString *object = _objects[indexPath.row];//_objects is mutable array holding the sentences or names
UITextField *textField = (UITextField *)[cell viewWithTag:100];//after that u are reusing the textfields
textField.text = object;
textField.tag = indexPath.row;
return cell;
}
now you are creating the cell thats wy u dont want the prototype cell remove it from story board
in the above u removed the custom cell becz u are creating the cell in the code it self
now in the method
- (void) textFieldDone:(UITextField *)inTextFIeld
{
int index = inTextFIeld.tag;
[_objects replaceObjectAtIndex:index withObject:[inTextFIeld text]];
[self.masterTableVIew reloadData];//made connection to ur tableview
}
I am having two labels created manually for displaying it in the tableviewcell named title and detail, code for displaying it are,
dealarray = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",nil];
detailarray = [[NSMutableArray alloc]initWithObjects:#"oneoneoneoneone oneoneoneoneoneoneoooooooo",#"two",#"three",#"fouronefouronefouronefouronefouronefouronefouron",nil];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
for(UILabel *lbl in [cell.contentView subviews])
{
[lbl removeFromSuperview];
}
cell.accessoryType= UITableViewCellAccessoryNone;
UILabel* title;
title= [[UILabel alloc] initWithFrame:CGRectMake(5,5,300,20)];
[cell.contentView addSubview:title];
[cell.contentView bringSubviewToFront:title];
[title setFont:[UIFont boldSystemFontOfSize:14]];
title.tag = 1001;
title.backgroundColor = [UIColor clearColor];
title.textColor = [UIColor blackColor];
title.text =[dealarray objectAtIndex:indexPath.row];
UILabel* detail;
detail= [[UILabel alloc] initWithFrame:CGRectMake(5,30,300,10)];
[cell.contentView addSubview:detail];
[cell.contentView bringSubviewToFront:detail];
[detail setFont:[UIFont systemFontOfSize:12]];
detail.tag = 1002;
detail.backgroundColor = [UIColor clearColor];
detail.textColor = [UIColor blackColor];
detail.text = [detailarray objectAtIndex:indexPath.row];
return cell
}
No problem in displaying those 2 labels and no problem in hiding all the 'detail' label and displaying the 'title' alone, the problem arises when I try to display the 'detail' label of the resp selective of cells.
Code tried:
// conti of cellforrowatindexpath
detail.numberOfLines = 3;
detail.lineBreakMode = NSLineBreakByWordWrapping;
if (a==-1)// declared 'a' in viewdidload as -1
{
((UILabel*)detail).hidden = YES;
}
else if(a==indexPath.row)
{
((UILabel*)detail).hidden = NO;
}
((UILabel*)detail).hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
a=indexPath.row;
[tableview reloadData];
}
Sorry for posting large amount of codes, it may help any one who is searching for the wholesome data of my doubt.
Whats the mistake am doing, I can't hide the detail label for resp selecting of cells. Can anybody help in this regard?
May I suggest you to use xcode functionnality to design your cell content? (as easy as drag and drop of UILabel on your cell for example) Then you will be able to access them from your code using their respective "tag" id.
A correct way of doing is detail here : http://www.appcoda.com/customize-table-view-cells-for-uitableview/
I think it's a better way than programmatically creating content for your cell, because using xcode interface you will be able to flawlessly define your interface.
Anyway to respond precisely to your question you should try to hide the detail label from "didSelectRowAtIndexPath" :
// Retrieve the corresponding cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// Get the detail label (using its tag) you set it to 1002
UILabel *detail = (UILabel *)[cell viewWithTag:1002];
// Hide it
detail.hidden = true;
Hope this help.
There is an error in your logic. You code as written will always set detail.hidden to YES, the 2 preceding if are ignored, thus this (BTW you don't need the type coercion and extra brackets):
if(a==-1) detail.hidden = YES;
else if (a==indexPath.row) detail.hidden = NO;
else detail.hidden = YES;