iOS Parse 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0] - ios

Im trying to add parse data into my table array and i get'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0] any help on how to resolve this would be appreciated.
PFQuery *query31 = [PFQuery queryWithClassName:#"Salesman"];
[query31 whereKey:#"SalesNo" equalTo:self.tbl22];
// query31.cachePolicy = kPFCachePolicyCacheThenNetwork;
[query31 getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!object) {
NSLog(#"The getFirstObject request failed.");
} else {
self.salesman = [object objectForKey:#"Salesman"];
NSLog(#"salesStr is %#",self.salesman);
}
}];
tableData2 = [NSArray arrayWithObjects:t21, t22, t23, t24, t25, nil];
here is were i get the crash t22 = self salesman
if ([_formController isEqual: #"Leads"]) {
if ( ( ![t22 isEqual:[NSNull null]] ) && ( [self.tbl22 length] != 0 ) )
{t22 = self.salesman;
} else { t22 = #"None"; }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([tableView isEqual:self.listTableView]) {
return [tableData count];
} else if ([tableView isEqual:self.listTableView2]) {
return [tableData count];
} else if ([tableView isEqual:self.newsTableView]) {
return 1;
}
return 0;
}
#pragma mark TableView Delegate Methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([tableView isEqual:self.listTableView]) {
static NSString *CellIdentifier = #"NewCell";
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (myCell == nil) {
myCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; }
//need to reload table (void)viewDidAppear to get fonts to change but its annoying
myCell.textLabel.text = [tableData4 objectAtIndex:indexPath.row];
myCell.textLabel.font = [UIFont systemFontOfSize:8.0];
[myCell.textLabel setTextColor:[UIColor darkGrayColor]];
myCell.detailTextLabel.text = [tableData objectAtIndex:indexPath.row];
myCell.detailTextLabel.font = [UIFont boldSystemFontOfSize:8.0];
[myCell.detailTextLabel setTextColor:[UIColor blackColor]];
return myCell;
}
else if ([tableView isEqual:self.listTableView2]) {
static NSString *CellIdentifier2 = #"NewCell2";
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (myCell == nil) {
myCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]; }
//need to reload table (void)viewDidAppear to get fonts to change but its annoying
myCell.textLabel.text = [tableData3 objectAtIndex:indexPath.row];
myCell.textLabel.font = [UIFont systemFontOfSize:8.0];
[myCell.textLabel setTextColor:[UIColor darkGrayColor]];
myCell.detailTextLabel.text = [tableData2 objectAtIndex:indexPath.row];
myCell.detailTextLabel.font = [UIFont boldSystemFontOfSize:8.0];
[myCell.detailTextLabel setTextColor:[UIColor blackColor]];
//draw red vertical line
UIView *vertLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, myCell.frame.size.height)];
vertLine.backgroundColor = [UIColor redColor];
[myCell.contentView addSubview:vertLine];
return myCell;
}
else if ([tableView isEqual:self.newsTableView]) {
static NSString *CellIdentifier1 = #"detailCell";
CustomTableViewCell *myCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1 forIndexPath:indexPath];
if (myCell == nil) {
myCell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]; }
//need to reload table (void)viewDidAppear to get fonts to change but its annoying
myCell.separatorInset = UIEdgeInsetsMake(0.0f, myCell.frame.size.width, 0.0f, 400.0f);
myCell.leadtitleLabel.text = self.lnewsTitle;
myCell.leadtitleLabel.numberOfLines = 0;
myCell.leadtitleLabel.font = [UIFont systemFontOfSize:12.0];
[myCell.leadtitleLabel setTextColor:[UIColor darkGrayColor]];
myCell.leadsubtitleLabel.text = #"Yahoo Finance 2 hrs ago";
myCell.leadsubtitleLabel.font = [UIFont systemFontOfSize:8.0];
[myCell.leadsubtitleLabel setTextColor:[UIColor grayColor]];
myCell.leadreadmore.text = #"Read more";
myCell.leadreadmore.font = [UIFont systemFontOfSize:8.0];
myCell.leadnews.text = comments;
myCell.leadnews.numberOfLines = 0;
myCell.leadnews.font = [UIFont boldSystemFontOfSize:8.0];
[myCell.leadnews setTextColor:[UIColor darkGrayColor]];
return myCell;
}
when i run log i get one result Salesman name
NSLog(#"salesStr is %#",self.salesman);
salesStr is Adam Monteleone

It means that you array is empty and you try to access the index 1 which is not able to get it. You better debug yourself.
And if you want to do the introspection on the NSString, you only need to use the length method to check. It will return false if your NSString is either nil or empty.

Related

Issues Creating Expandable Table iOS - Objective-C

I am trying to create an expandable table view, however when I click on one of the cells I load a .xib file to format the subviews, however when I click the cell again the .xib format remains and messes with the view of the cells. Is there a better way to make the expandable table view?
Code:
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 28;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self tableView:tableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return [ticketList count];
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 72;
}
Load the xib here:
- (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:#"reuse"];
}
// Configure the cell...
NSLog(#"Number: %d", indexPath.section);
NSArray *items = [[NSArray alloc] initWithObjects:#"Cleanliness", #"Door", #"Peek Hole", #"Sink", #"Towel Rack", #"Closet", #"Carpet", #"Wall", #"Bed", #"Matress", #"Mattress Cover", #"Fridge", #"Blinds", #"Window", #"Screen", #"Air Conditioning", #"Chair", #"Desk", #"Garbage bin", #"Shelves", #"Phone", #"Jacks", #"Lights", #"Smoke Detector", #"Heat Detector", #"Light bulb", #"Deep Cleaning", #"Final Prep", nil];
if (!indexPath.row)
{
// first row
cell.textLabel.text = items[indexPath.section]; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
}
else
{
}
}
else
{
[self.tableView registerNib:[UINib nibWithNibName:#"HelpDeskCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
static NSString *CellIdentifier = #"Cell";
HelpDeskCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[HelpDeskCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
CGFloat fontsize = 16;
if([[[ticketList objectAtIndex:indexPath.row] objectForKey:#"priority"] isEqualToString:#"Critical"]){
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:1 green:0.5 blue:0.5 alpha:1.0]];
}
else{
[cell.IDLabel setBackgroundColor:[UIColor colorWithRed:0.925 green:0.925 blue:0.925 alpha:1.0]];
}
[cell.IDLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
//reduce fontsize to 12 for the information labels
//same on all devices and orientations
fontsize = 12;
//ticket status label
[cell.statusLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.statusLabel setTextColor:[UIColor whiteColor]];
//ticket category label
[cell.categoryLabel setBackgroundColor:[UIColor grayColor]];
[cell.categoryLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.categoryLabel setTextColor:[UIColor whiteColor]];
//ticket title label
[cell.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
[cell.titleLabel setTextColor:[UIColor blackColor]];
//Label holds the user that submitted the ticket
[cell.submittedLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.submittedLabel setTextColor:[UIColor blackColor]];
//Label holds the user currently working on the ticket
[cell.handleLabel setFont:[UIFont systemFontOfSize:fontsize]];
[cell.handleLabel setTextColor:[UIColor blackColor]];
//ticket date label
[cell.dateLabel setFont:[UIFont systemFontOfSize:fontsize]];
// Set the text of the subviews
NSString * ticketIdStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"ticket_id"];
[cell.IDLabel setText:ticketIdStr];
NSString * ticketStatusStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"status"];
[cell.statusLabel setText:ticketStatusStr];
if([ticketStatusStr isEqualToString:#"Open"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0 green:0.6 blue:0.8 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"In Progress"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:1.0 green:0.733 blue:0.2 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Resolved"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.6 green:0.8 blue:0 alpha:1.0]];
}
else if ([ticketStatusStr isEqualToString:#"Closed"]) {
[cell.statusLabel setBackgroundColor: [UIColor colorWithRed:0.8 green:0 blue:0 alpha:1.0]];
}
NSString * categoryStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"category"];
[cell.categoryLabel setText:categoryStr];
NSString * titleStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"title"];
NSString * userIDStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"user_id"];
NSString * handledByStr = [[ticketList objectAtIndex:indexPath.row] objectForKey:#"handled_by"];
[cell.titleLabel setText: [NSString stringWithFormat:#"Title: %#", titleStr]];
[cell.submittedLabel setText: [NSString stringWithFormat:#"Submitted By: %#", userIDStr]];
[cell.handleLabel setText: [NSString stringWithFormat:#"Handled By: %#", handledByStr]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *orignalDate = [dateFormatter dateFromString:[[[ticketList objectAtIndex:indexPath.row] objectForKey:#"date_submitted"] substringToIndex:10]];
[dateFormatter setDateFormat:#"MMMM dd, yyyy"];
NSString * ticketDateStr = [dateFormatter stringFromDate:orignalDate];
[cell.dateLabel setText:ticketDateStr];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
return cell;
}
Expand and Collapse here:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
[self.tableView reloadData];
}
}
Update
The main cell is a list of items and the expanding cell is suppose to be tickets from a sql database. I use a xib file to format the tickets
but when I collapse the cell which contains the items, this image remains and covers up the item cells
For creating expandable table view on clicking of UITableViewCell simply add a new cell in existing UITableView
[self.tableview insertRowsAtIndexPath:indexPath
withRowAnimation:UITableViewRowAnimationAutomatic];

-[__NSArrayM length]: unrecognized selector sent to instance 0x145ecca0

am getting the following error, cannot figure it out where it is. Please help me to find out the issue. TIA
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM length]: unrecognized selector sent to instance 0x145ecca0'
*** First throw call stack:
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:#"Helvetica neue" size:20.0];
//label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
//label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor]; // change this color
self.navigationItem.titleView = label;
label.text = #"My Details";
[label sizeToFit];
}
#pragma mark -
#pragma mark Table view data source
- (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 30;
}
// 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 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.textLabel.font=[UIFont fontWithName:#"Helvetica neue" size:14.0];
cell.detailTextLabel.font=[UIFont fontWithName:#"Helvetica neue" size:13.0];
cell.textLabel.textColor=[UIColor colorWithRed:199.0/255.0 green:65.0/255.0 blue:69.0/255.0 alpha:1.0];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
NSArray *keys = [myDict allKeys];
for(int i=0 ; i<[keys count]; i++ )
{
NSString *value=[myDict objectForKey:[keys objectAtIndex:i]];
if ([value isEqual: [NSNull null]]||[value length]==0) {
[myDict setValue:#"--" forKey:[keys objectAtIndex:i]];
}
}
if(indexPath.row==0)
{
cell.textLabel.text = #"Relationship";
cell.detailTextLabel.text=[myDict objectForKey:#"Relationship"];
}
if(indexPath.row==1)
{
cell.textLabel.text = #"Person Name";
cell.detailTextLabel.text=[myDict objectForKey:#"PersonName"];
}
if(indexPath.row==2)
{
cell.textLabel.text = #"Shopping";
cell.detailTextLabel.text=[myDict objectForKey:#"shopping"];
}
if(indexPath.row==3)
{
cell.textLabel.text = #"Quantity";
cell.detailTextLabel.text=[myDict objectForKey:#"Quantity"];
}
if(indexPath.row==4)
{
cell.textLabel.text = #"Pants";
cell.detailTextLabel.text=[myDict objectForKey:#"pants"];
}
if(indexPath.row==5)
{
cell.textLabel.text = #"Shirts";
cell.detailTextLabel.text=[myDict objectForKey:#"shirts"];
}
if(indexPath.row==6)
{
cell.textLabel.text = #"Other";
cell.detailTextLabel.text=[myDict objectForKey:#"other"];
}
if(indexPath.row==7)
{
cell.textLabel.text = #"Start Date";
NSString *str=[myDict objectForKey:#"startDate"];
NSString *str2= [str substringToIndex:10];
cell.detailTextLabel.text=str2;
}
if(indexPath.row==8)
{
cell.textLabel.text = #"End Date";
NSString *str=[myDict objectForKey:#"endDate"];
NSString *str2= [str substringToIndex:10];
cell.detailTextLabel.text=str2;
}
if(indexPath.row==9)
{
cell.textLabel.text = #"Address";
cell.detailTextLabel.text=[myDict objectForKey:#"address"];
}
if(indexPath.row==10)
{
cell.textLabel.text = #"Notes";
cell.detailTextLabel.text=[myDict objectForKey:#"Notes"];
}
if(indexPath.row==11)
{
cell.textLabel.text = #"Bill";
cell.detailTextLabel.text=[myDict objectForKey:#"bill"];
}
if(indexPath.row==12)
{
cell.textLabel.text = #"Grand Total";
cell.detailTextLabel.text=[myDict objectForKey:#"total"];
}
if(indexPath.row==13)
{
cell.textLabel.text = #"Signature";
cell.detailTextLabel.text=[myDict objectForKey:#"sign"];
}
return cell;
}
NSArray do not respond to length, but count.
Most probably in value you expect a NSString, but there is an array instead.
Something is wrong when you set the value.
Might be you are expecting something different and it having other type of values.May be you are expecting NSString and it is giving any other type.
Youc can use id data type so that it can be helpful. This solved for me.Hope for you also.
This:
[myDict objectForKey:[keys objectAtIndex:i]];
is returning an NSArray, not a NSString.

How to set a Bool value to be different for each UITableView Section

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

UIImageView in UITableViewCell repeat

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

UITextField display issue in TableView cell

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;

Resources