I have 5 seperate sections in a table, 2 of the sections have customizable cells, when in EDITING mode, 2 of the sections produce an additional cell that will add a new cell to the list. My problem is that when I invoke edit mode, the UISwitch glitches! and decides to jump around, VERY SIMPLE code, just have NO IDEA why the UISwitch is jumping to different cells in DIFFERENT SECTIONS when it should NOT!
static NSInteger kCustomTextTag = 1;
static NSInteger kServiceTag = 3;
static NSInteger kConnectTag = 4;
static NSInteger kVibrateTag = 1;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Profile_ManagerAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.hidesAccessoryWhenEditing = YES;
}
UISwitch *swService = nil;
swService = [[[UISwitch alloc] initWithFrame:CGRectMake(195, 8, 160, 27)] autorelease];
[swService addTarget:self action:#selector(serviceSwAction:) forControlEvents:UIControlEventValueChanged];
swService.tag = kServiceTag;
UISwitch *swConnect = nil;
swConnect = [[[UISwitch alloc] initWithFrame:CGRectMake(195, 8, 160, 27)] autorelease];
[swConnect addTarget:self action:#selector(connectSwAction:) forControlEvents:UIControlEventValueChanged];
swConnect.tag = kConnectTag;
UISwitch *swVibrate = nil;
swVibrate = [[[UISwitch alloc] initWithFrame:CGRectMake(195, 8, 160, 27)] autorelease];
[swVibrate addTarget:self action:#selector(vibrateSwAction:) forControlEvents:UIControlEventValueChanged];
swVibrate.tag = kVibrateTag;
if(indexPath.section == 0)
{
//CGRectMake Method (x, y, width, height)
custProfileNameLabel = [[[UITextField alloc] initWithFrame:CGRectMake(10, 11, 290, 21)] autorelease];
custProfileNameLabel.tag = kCustomTextTag;
custProfileNameLabel.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:custProfileNameLabel];
custProfileNameLabel.backgroundColor = [UIColor clearColor];
custProfileNameLabel.userInteractionEnabled = NO;
custProfileNameLabel.placeholder = #"Custom Profile Name";
custProfileNameLabel.autocapitalizationType = UITextAutocapitalizationTypeWords;
custProfileNameLabel.clearButtonMode = UITextFieldViewModeWhileEditing;
//UIKeyboardTypeDefault;
cell.selectionStyle = UITableViewCellEditingStyleNone;
CustomProfile *cProf = [CustomProfile alloc];
cell.textLabel.text = [cProf tName];
}
if(indexPath.section == 1)
{
if(indexPath.row == ([[appDelegate serviceArray] count]) && self.editing){
cell.textLabel.text = #"Add a Service";
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
swService.hidden = YES;
return cell;
}else{
swService.hidden = NO;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [[appDelegate serviceArray] objectAtIndex:indexPath.row];
}
[cell addSubview:swService];
}
if(indexPath.section == 2)
{
if(indexPath.row == ([[appDelegate connectArray] count]) && self.editing){
cell.textLabel.text = #"Add a Connection";
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
swConnect.hidden = YES;
return cell;
}else{
swConnect.hidden = NO;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [[appDelegate connectArray] objectAtIndex:indexPath.row];
}
[cell addSubview:swConnect];
}
if(indexPath.section == 3)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPlistPath = [documentsDirectory stringByAppendingPathComponent:#"ProfileManager.plist"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:myPlistPath];
NSString *value;
value = [plistDict objectForKey:#"Custom Ringtone"];
if(indexPath.row == ([[appDelegate ringArray] count]) && self.editing){
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
}else{
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = value;
}
if(indexPath.section == 4)
{
if(indexPath.row == 0 && self.editing)
{
//cell.userInteractionEnabled = NO;
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = #"Vibrate";
swVibrate.hidden = YES;
}else{
swVibrate.hidden = NO;
//cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.text = #"Vibrate";
}
[cell.contentView addSubview:swVibrate];
}
return cell;
}
Screenshot
Well, the reason this glitch was made possible is because the Controls were created when creating the cell, so it just continued to create additional controls when view appeared.
If you are receiving this glitch too, make sure you create the controls at ViewDidLoad, or call a void, just dont create the controls in the cellForRowAtIndexPath:
Nothing freaky is going on. This is normal behavior. Note the line UITableViewCell *cell = dequeueReusableCellWithIdentifier ... The tableview controller keeps a queue of previously used cells for efficiency purposes, and when you scroll a new section of the tableview into view, it may return a previously used cell for you to reuse (in which case the value of the returned cell would not be nil). If that used cell originally had a uiswitch embedded in it, you'll get that switch back again, even if the current cell doesn't use it.
You need to check in your cell allocation code whether the cell being given back to you is an existing one or not, and remove the switch if it's present and you don't want it.
Howard
Related
Due to some permission issue, in my tableView some cell can be selected by user and some cell can't be selected by that user. What I did in my cellForRowAtIndexPath is:
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
int row = (int)[indexPath row];
static NSString *simpleTableIdentifier = #"EditProjectTableCell";
Project* project = (Project*)[self.projectList objectAtIndex:row];
EditProjectTableCell *cell = (EditProjectTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:simpleTableIdentifier owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.serial.layer.cornerRadius = 5;
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:#"accessory_right.png"]];
cell.cellView.backgroundColor = [UIColor blackColor];
cell.backgroundColor = [UIColor blackColor];
}
if ([project.role isEqualToString:#"1"] || [project.role isEqualToString:#"2"]) {
UIView *customView = [[UIView alloc] initWithFrame:cell.frame];
customView.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = customView;
}
else cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(cell.imageFetchOperation != nil) [cell.imageFetchOperation cancel];
cell.imageFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:YES
andFetchReportCounter:NO
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
if(cell.counterFetchOperation != nil) [cell.counterFetchOperation cancel];
cell.counterFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:NO
andFetchReportCounter:YES
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
cell.projectName.text = project.name;
cell.projectNumber.text = project.number;
cell.owner.text = [NSString stringWithFormat:#"%# %#",project.ownerName,project.ownerLastName];
NSString* temp_date = [Utils stringFromDateForGUI:project.creationDate];
cell.date.text = temp_date;
[cell.syncStatusView setImage:[Utils getImageForSyncStatus:project.isDirty.intValue]];
NSNumber *ret = [self.reportCountList objectForKey:project.pkId];
if(ret == nil) {
cell.serial.text = #"";
[cell.counterFetchOperation setPkId:project.pkId];
[self.tableCellUpdateQueue addOperation:cell.counterFetchOperation];
} else {
cell.serial.text = [NSString stringWithFormat:#"%d",[ret intValue]];
}
id img = [self getSmallImage:project.pkId andIndexPath:indexPath andCell:cell];
if(img == nil || img == (id)[NSNull null]) {
img = [UIImage imageNamed:#"gray-img.jpg"];
cell.iconImageView.image = [UIImage imageNamed:#"project-icon.png"];
cell.iconImageView.hidden = NO;
} else {
cell.iconImageView.hidden = YES;
}
cell.imageView.image = (UIImage*)img;
if ([project.role isEqualToString:#"2"] || [project.role isEqualToString:#"1"])
cell.selectImageView.hidden = NO;
else
cell.selectImageView.hidden = YES;
return cell;
}
Selection part is working just fine. But if a cell is selected then the background color of a UILabel gets changed to clear color. See the below images for clear idea.
Before selection:
After Selection :
What I want to do here is set it so that if top3ArrayForSection.count-1 < 1, set the _results bool value of that respective section to NO, and so on. What's happening instead, is that _results is set to NO or YES for the entire table overall, so that I end up with a result like this:
When only the "xperia Z3 compact unlocked" section should say "no items found etc." because it has no cells, the other sections cells shouldn't.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *currentSectionDictionary = _matchCenterArray[section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
if (top3ArrayForSection.count-1 < 1){
_results = NO;
_rowCount = 1;
}
else if(top3ArrayForSection.count-1 >= 1){
_results = YES;
_rowCount = top3ArrayForSection.count-1;
}
return _rowCount;
}
// Cell layout
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
if (_results == NO) {
// title of the item
cell.textLabel.text = #"No items found, but we'll keep a lookout for you!";
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
}
else if (_results == YES) {
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
}
return cell;
}
Your instance variable _results is one-dimensional. You could replace it with an NSArray and store the values individually, or you could change the logic in your code as such:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *currentSectionDictionary = _matchCenterArray[section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
return (top3ArrayForSection.count-1 < 1) ? 1 : top3ArrayForSection.count-1;
}
// Cell layout
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
NSDictionary *currentSectionDictionary = _matchCenterArray[indexPath.section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
if (top3ArrayForSection.count-1 < 1) {
// title of the item
cell.textLabel.text = #"No items found, but we'll keep a lookout for you!";
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
}
else {
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
}
return cell;
}
I am trying to create tableview with UISwitch for some specific rows and AccessoryDisclosureIndicator for rest of cells.
I get the desired result as one check in following code.But the issue is , when i scroll the table view abruptly then the position of switch changes .. Which is undesired how can i get rid of this.
Please do reply to this thread
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
int _fontSize = fontSize;
NSArray *switchSettings = [[NSUserDefaults standardUserDefaults] arrayForKey:#"switchGeneralSettings"];
NSLog(#"switch settings :%#",switchSettings);
static NSString *cellIdentifier = #"generalSettingsTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSLog(#"*******************1*************");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
// code to additionally configure cell for multiple other UI components..
if(indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7)
{
NSLog(#"switch*******************%d*************",indexPath.row);
switchObj = [[UISwitch alloc] initWithFrame:CGRectZero];
switchObj.tag = indexPath.row + 20002;
cell.accessoryView = switchObj;
[switchObj addTarget: self action: #selector(flip:) forControlEvents:UIControlEventValueChanged];
[switchObj release];
}
else
{
NSLog(#"indicator*******************%d*************",indexPath.row);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
else
{
if(indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7)
{
NSLog(#"*******************2*************");
countSwitch = 0;
switchObj = (UISwitch *)[cell.contentView viewWithTag:indexPath.row + 20002];
// switch
[switchObj setOn:NO];
if ([switchSettings count]>0) {
NSString *settingState = [switchSettings objectAtIndex:countSwitch];
if ([settingState isEqualToString:#"ON"]) {
[switchObj setOn:YES];
}
}
countSwitch++;
}
}
// confiure the cell here...
NSLog(#"*******************3*************");
NSString *cellTextLabel = [listGeneralSettings objectAtIndex:indexPath.row];
cell.textLabel.text = cellTextLabel;
cell.textLabel.font = [UIFont systemFontOfSize:_fontSize];
cell.detailTextLabel.text = [listDetailGeneralSettings objectAtIndex:indexPath.row];
NSLog(#" cell.detailTextLabel.text :%#", cell.detailTextLabel.text);
NSLog(#"*******************end*************");
return cell;
}
Here cellone is tableviewCell, in that cell you can add uiswitch
(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];
// ... some text label stuff deleted here.
cell.opaque = NO;
cell.selectionStyle = UITableViewCellSelectionStyleGray;
[cell setBackgroundColor: [UIColor colorWithPatternImage:[UIImage imageNamed:#"row_2_blank.png"]]];
// [cell prepareForReuse];
}
if (indexPath.row == 0)
{
selectAllB.tag=100;
[selectAllB addTarget:self action:#selector(click:)forControlEvents:UIControlEventTouchUpInside];
[cellOne setBackgroundColor: [UIColor colorWithPatternImage:[UIImage imageNamed:#"row_2_blank.png"]]];
cellOne.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cellOne;
}
return cell;
}
likewise you can use many tableview cell inwhich you can add ui elements accordingly
You're only updating the cell when it's first created. You need to update it every time. Try it like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
int _fontSize = fontSize;
NSArray *switchSettings = [[NSUserDefaults standardUserDefaults] arrayForKey:#"switchGeneralSettings"];
NSLog(#"switch settings :%#",switchSettings);
static NSString *cellIdentifier = #"generalSettingsTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSLog(#"*******************1*************");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
// code to additionally configure cell for multiple other UI components..
// configure the cell here...
if(indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7)
{
NSLog(#"switch*******************%d*************",indexPath.row);
switchObj = [[UISwitch alloc] initWithFrame:CGRectZero];
switchObj.tag = indexPath.row + 20002;
cell.accessoryView = switchObj;
[switchObj addTarget: self action: #selector(flip:) forControlEvents:UIControlEventValueChanged];
[switchObj release];
}
else
{
NSLog(#"indicator*******************%d*************",indexPath.row);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if(indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7)
{
NSLog(#"*******************2*************");
countSwitch = 0;
switchObj = (UISwitch *)[cell.contentView viewWithTag:indexPath.row + 20002];
// switch
[switchObj setOn:NO];
if ([switchSettings count]>0) {
NSString *settingState = [switchSettings objectAtIndex:countSwitch];
if ([settingState isEqualToString:#"ON"]) {
[switchObj setOn:YES];
}
}
countSwitch++;
}
NSLog(#"*******************3*************");
NSString *cellTextLabel = [listGeneralSettings objectAtIndex:indexPath.row];
cell.textLabel.text = cellTextLabel;
cell.textLabel.font = [UIFont systemFontOfSize:_fontSize];
cell.detailTextLabel.text = [listDetailGeneralSettings objectAtIndex:indexPath.row];
NSLog(#" cell.detailTextLabel.text :%#", cell.detailTextLabel.text);
NSLog(#"*******************end*************");
return cell;
}
I have a bug.
I want to display a UIImageView on cells at special indexPath.row, but these UIImageView repeat while I scroll.
Exemple: I display my UIImageView on a cell indexPath.row == 0, if I scroll down, I see my UIImageView on the cell at indexPath.row == 8.
Here is my code:
// 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) {
cell = [self getCellContentView:CellIdentifier];
}
UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];
UIImageView *imgRead = (UIImageView *)[cell viewWithTag:6];
[cell.contentView insertSubview:imgRead aboveSubview:lblTemp1];
contentDictio = [dict objectAtIndex:indexPath.row];
lblTemp1.text = [contentDictio objectForKey:#"title"];
NSArray *paths_id = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath_id = ([paths_id count] > 0) ? [paths_id objectAtIndex:0] : nil;
NSString *path_id = [basePath_id stringByAppendingPathComponent:#"id.plist"];
NSMutableArray *mut_array_id = [[NSArray arrayWithContentsOfFile:path_id] mutableCopy];
NSMutableDictionary *c0 = [[NSMutableDictionary alloc] init];
NSString *idPlistData = [contentDictio objectForKey:#"id"];
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
}
else {
}
}
}
return cell;
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {
CGRect Label1Frame = CGRectMake(kTableCellSmallMargin*2 + 60, kTableCellSmallMargin, 240, 25);
UILabel *lblTemp;
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier] autorelease];
//Initialize Label with tag 1.
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = 1;
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setFont: [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:15.0]];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
UIImageView *read=[[UIImageView alloc] initWithFrame:CGRectMake(kTableCellSmallMargin, kTableCellSmallMargin, 60, 60)];
read.backgroundColor=[UIColor clearColor];
read.tag = 6;
[cell.contentView addSubview:read];
[read release];
return cell;
}
Thanks...
The cell is cached, so you have to clear it when you want no image, like this:
BOOL found = NO;
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
found = YES;
}
else {
}
}
if (!found)
{
[imgRead setImage:nil];
}
I created at least 10 cells with each UITextField on it, for registration page. When I insert the words on the textfield in the first cell, and when I scrolled the tableView, the textfield which is in another cell show up the word that I just typed.
Below is my code. The textField data which I input is looping, which is caused by dequeueReusableCellWithIdentifier... How can I solve this problem? Thank you very much.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"RCell";
RegisterCell *cell = (RegisterCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[[RegisterCell alloc] initWithFrame:CGRectMake(0, 0, 280, 44) reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.section == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
UITextField *valTxtField = [[UITextField alloc] initWithFrame:CGRectMake(120, 5, 180, 30)];
valTxtField.font = [UIFont fontWithName:#"Futura-CondensedExtraBold" size:18.0];
valTxtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
valTxtField.delegate = self;
valTxtField.returnKeyType = UIReturnKeyDone;
valTxtField.autocorrectionType = UITextAutocorrectionTypeNo;
valTxtField.autocapitalizationType = UITextAutocapitalizationTypeNone;
if(indexPath.row == 0)
{
valTxtField.text = #"";
emailTxtFld = valTxtField; //emailTxtFld is global variable
}
if(indexPath.row == 1)
{
valTxtField.text = #"";
reEmailTxtFld = valTxtField; //reEmailTxtFld is global variable
}
[cell.contentView addSubview:valTxtField];
[valTxtField release];
}
else if(indexPath.section == 1){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+10];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
else if(indexPath.section == 2){
if(indexPath.row == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+11];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
}
return cell;
}
An easy way is to just remove all subviews from the cells contentView before you add subviews, example:
for (UIView *subview in [cell.contentView subviews])
[subview removeFromSuperview];
A more efficient way would be to do all the creation of cells inside the if (cell == nil) statement, but that depends on how many cells you have in the table.
The right implementation is to move the creation of any view whithin if (cell == nil)
Like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"RCell";
RegisterCell *cell = (RegisterCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *valTxtField;
if (cell == nil)
{
cell = [[[RegisterCell alloc] initWithFrame:CGRectMake(0, 0, 280, 44) reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.section == 0){
valTxtField = [[UITextField alloc] initWithFrame:CGRectMake(120, 5, 180, 30)];
valTxtField.font = [UIFont fontWithName:#"Futura-CondensedExtraBold" size:18.0];
valTxtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
valTxtField.delegate = self;
valTxtField.returnKeyType = UIReturnKeyDone;
valTxtField.autocorrectionType = UITextAutocorrectionTypeNo;
valTxtField.autocapitalizationType = UITextAutocapitalizationTypeNone;
valTxtField.tag = 100;
[cell.contentView addSubview:valTxtField];
[valTxtField release];
}
}
valTxtField = (UITextField *)[cell.contentView viewWithTag:100];
if(indexPath.section == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
if(indexPath.row == 0)
{
valTxtField.text = #"";
emailTxtFld = valTxtField; //emailTxtFld is global variable
}
if(indexPath.row == 1)
{
valTxtField.text = #"";
reEmailTxtFld = valTxtField; //reEmailTxtFld is global variable
}
}
else if(indexPath.section == 1){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+10];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
else if(indexPath.section == 2){
if(indexPath.row == 0){
NSDictionary *rowData = [self.regisLabel objectAtIndex:[indexPath row]+11];
NSString *mainLabel = [NSString stringWithFormat:#"%#", [rowData objectForKey:#"regisLbl"]];
cell.registerLabel.text = mainLabel;
cell.registerTextField.enabled = NO;
}
}
return cell;