overlapping issue on table view cell - iphone

I am getting overlapping issue while using following code. I used custom cell and normal cell style for this form.
Any suggestion is appreciated
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *RSVNIdentifier = #"RSVNCell";
CreateReservationViewCell *cell = (CreateReservationViewCell *)[tableView dequeueReusableCellWithIdentifier:RSVNIdentifier] ;
if (cell == nil) {
cell = [[[CreateReservationViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RSVNIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if(indexPath.section == 0)
{
{
if(indexPath.row == 0){
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.editing =NO;
cell.m_rsvn_name.text =#"Customer";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"reservation"] objectForKey:#"createdBy"];
cell.m_rsvn_value.enabled=NO;
return cell;
}
if(indexPath.row == 1){
cell.m_rsvn_name.text =#"Till";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"reservation"] objectForKey:#"createdDate"];
cell.m_rsvn_value.enabled=NO;
return cell;
}
if(indexPath.row == 2){
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
emailTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
emailTextField.adjustsFontSizeToFitWidth = YES;
emailTextField.font = [UIFont systemFontOfSize:12];
emailTextField.textAlignment= UITextAlignmentRight;
emailTextField.keyboardType= UIKeyboardTypeEmailAddress;
emailTextField.returnKeyType = UIReturnKeyDone;
emailTextField.tag=0;
emailTextField.delegate=self;
emailTextField.text =[textFields objectAtIndex:0];
cell.m_rsvn_name.text =#"Email";
[cell addSubview:emailTextField];
return cell;
}
if(indexPath.row == 3){
cell.m_rsvn_name.text =#"Telephone";
phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
phoneTextField.adjustsFontSizeToFitWidth = YES;
phoneTextField.font = [UIFont systemFontOfSize:12];
phoneTextField.textAlignment= UITextAlignmentRight;
phoneTextField.keyboardType= UIKeyboardTypePhonePad;
phoneTextField.delegate=self;
phoneTextField.tag=1;
phoneTextField.text =[textFields objectAtIndex:1];
cell.m_rsvn_name.text =#"Phone";
[cell addSubview:phoneTextField];
return cell;
}
if(indexPath.row == 4){
cell.m_rsvn_name.text =#"Internal Note";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"reservation"] objectForKey:#"internalNote"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.m_rsvn_value.enabled=NO;
return cell;
}
}
}
else if(indexPath.section == 1){
NSLog(#"%#",unit_details);
//[[create_reservation_detail objectAtIndex:0] objectForKey:#"reservation"] objectForKey:#"unitName"];
for (int i=0; i<[unit_details count]; i++) {
if(indexPath.row == i){
cell.m_unit_title.text = [[unit_details objectAtIndex:0] objectForKey:#"unitName"];
cell.m_unit_value1.text = [[unit_details objectAtIndex:0] objectForKey:#"nights"];
cell.m_unit_value2.text =[[unit_details objectAtIndex:0] objectForKey:#"adults"];
return cell;
}
}
}
else if(indexPath.section == 2){
if(indexPath.row == 0){
cell.m_rsvn_name.text = #"Total Charges";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"charges"] objectForKey:#"totalRoomCharge"];
return cell;
}
if(indexPath.row == 1){
cell.m_rsvn_name.text = #"10% Tax";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"charges"] objectForKey:#"roomTaxAmount"];
return cell;
}
if(indexPath.row == 2){
cell.m_rsvn_name.text = #"Total Charges1";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"charges"] objectForKey:#"otherCharge"];
return cell;
}
if(indexPath.row == 3){
cell.m_rsvn_name.text = #"Total Charges2";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"charges"] objectForKey:#"totalCharge"];
return cell;
}
if(indexPath.row == 4){
cell.m_rsvn_name.text = #"Total Payments";
//cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"charges"] objectForKey:#"totalPayment"];
return cell;
}
if(indexPath.row == 5){
cell.m_rsvn_name.text = #"Current Balance";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"charges"] objectForKey:#"currentBalance"];
return cell;
}
}
else if(indexPath.section == 3){
if(indexPath.row == 0){
cell.m_rsvn_name.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"deposit"] objectForKey:#"description"];
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"deposit"] objectForKey:#"amount"];
return cell;
}
else if(indexPath.row == 1){
cell.m_rsvn_name.text =#"Amount Due";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"deposit"] objectForKey:#"amount_due"];
return cell;
}
else if(indexPath.row == 2){
cell.m_rsvn_name.text =#"Security Deposit status";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"deposit"] objectForKey:#"securityStatus"];
return cell;
}
else if(indexPath.row == 3){
cell.m_rsvn_name.text =#"Security Deposit Due";
cell.m_rsvn_value.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"deposit"] objectForKey:#"securityStatus_due"];
return cell;
}
else if(indexPath.row == 4){
static NSString *SecurityCellIdentifier = #"Cell";
UITableViewCell *security_cell = [tableView dequeueReusableCellWithIdentifier:SecurityCellIdentifier];
if (security_cell == nil) {
security_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SecurityCellIdentifier] autorelease];
}
// Configure the cell...
security_cell.textLabel.text = #"Security Deposit Instruction:";
security_cell.textLabel.font = [UIFont systemFontOfSize:14];
security_cell.detailTextLabel.text =[[[create_reservation_detail objectAtIndex:0] objectForKey:#"deposit"] objectForKey:#"instruction"];
security_cell.textLabel.font = [UIFont systemFontOfSize:14];
security_cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
security_cell.detailTextLabel.numberOfLines = 0;
[security_cell.detailTextLabel sizeToFit];
return security_cell;
}
}
else if(indexPath.section == 4){
static NSString *Payment_CellIdentifier = #"Payment_Cell";
UITableViewCell *pay_cell = [tableView dequeueReusableCellWithIdentifier:Payment_CellIdentifier];
if (!pay_cell) {
pay_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Payment_CellIdentifier] autorelease];
}
pay_cell.textLabel.font=[UIFont systemFontOfSize:14];
if(indexPath.row == 0){
if ([[[[create_reservation_detail objectAtIndex:0] objectForKey:#"payment"] objectForKey:#"paypal"] isEqualToString:#""])
{
pay_cell.accessoryType=UITableViewCellAccessoryNone;
pay_cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else
{
pay_cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
NSLog(#"accessory type ->%d",cell.accessoryType);
pay_cell.textLabel.text = #"PayPal";
pay_cell.selectionStyle = UITableViewCellSelectionStyleGray;
pay_cell.detailTextLabel.text=[[[create_reservation_detail objectAtIndex:0] objectForKey:#"payment"] objectForKey:#"paypal"];
pay_cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
pay_cell.detailTextLabel.numberOfLines = 0;
[pay_cell.detailTextLabel sizeToFit];
return pay_cell;
}
if(indexPath.row == 1){
if ([[[[create_reservation_detail objectAtIndex:0] objectForKey:#"payment"] objectForKey:#"manualCheck"] isEqualToString:#""])
{
pay_cell.accessoryType=UITableViewCellAccessoryNone;
pay_cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else
{
pay_cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
NSLog(#"accessory type ->%d",cell.accessoryType);
pay_cell.textLabel.text = #"Manual Check";
pay_cell.selectionStyle = UITableViewCellSelectionStyleGray;
pay_cell.selectionStyle = UITableViewCellSelectionStyleGray;
pay_cell.detailTextLabel.text=[[[create_reservation_detail objectAtIndex:0] objectForKey:#"payment"] objectForKey:#"manualCheck"];
pay_cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
pay_cell.detailTextLabel.numberOfLines = 0;
[pay_cell.detailTextLabel sizeToFit];
return pay_cell;
}
if(indexPath.row == 2){
if ([[[[create_reservation_detail objectAtIndex:0] objectForKey:#"payment"] objectForKey:#"tranfer"] isEqualToString:#""])
{
pay_cell.accessoryType=UITableViewCellAccessoryNone;
NSLog(#"accessory type ->%d",UITableViewCellAccessoryCheckmark);
pay_cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else
{
pay_cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
NSLog(#"accessory type ->%d",UITableViewCellAccessoryCheckmark);
pay_cell.textLabel.text = #"Wire / Transfer";
pay_cell.selectionStyle = UITableViewCellSelectionStyleGray;
pay_cell.selectionStyle = UITableViewCellSelectionStyleGray;
pay_cell.detailTextLabel.text=[[[create_reservation_detail objectAtIndex:0] objectForKey:#"payment"] objectForKey:#"tranfer"];
pay_cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
pay_cell.detailTextLabel.numberOfLines = 0;
[pay_cell.detailTextLabel sizeToFit];
return pay_cell;
}
if(indexPath.row == 3){
other.borderStyle=UITextBorderStyleRoundedRect;
other.placeholder=#"other\n";
other.autocorrectionType=UITextAutocorrectionTypeNo;
other.delegate=self;
other.autocapitalizationType=UITextAutocapitalizationTypeNone;
other.hidden=[[textFields objectAtIndex:2] intValue];
other.returnKeyType = UIReturnKeyDone;
[pay_cell addSubview:other];
pay_cell.textLabel.text = #"Other";
pay_cell.selectionStyle = UITableViewCellSelectionStyleGray;
return pay_cell;
}
}
else {
if(indexPath.row == 0){
static NSString *Button_CellIdentifier = #"Button_Cell";
UITableViewCell *button_cell = [tableView dequeueReusableCellWithIdentifier:Button_CellIdentifier];
if (button_cell == nil)
{
button_cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:Button_CellIdentifier] autorelease];
}
button_cell.backgroundView= [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"save_reservation_button.png"]] autorelease];
button_cell.selectedBackgroundView= [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"save_reservation_button.png"]] autorelease];
return button_cell;
}
}
return nil;
}
Regards,
sathish

You should make custom view added to cell inside the block
if (cell == nil) {
cell = [[[CreateReservationViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RSVNIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// deal with your custom views here
}
For example, this codes will make one more sub-views on the cell. If this cell is come from dequeue, it already has a emailTextField added on this cell, and following code will add one more emailTextField on this cell.
if(indexPath.row == 2){
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
emailTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
... // assign emailTextField settings
cell.m_rsvn_name.text =#"Email";
[cell addSubview:emailTextField];
return cell;
}

where overlapping is happening. means on cell item or anywhere else. and in code somewhere u using [cell addSubView] instead of that use [cell.contentView addSubView]

Related

i have issue with prototype table view cell that my cell text is overlapping every time when it get used

This is my code every time when i scroll my labels text are getting overleaped.Text are overlapping and i think this is because reuse of cell.
I am using storyboard and this is not a custom cell.
Need some help,every single help would be appreciated.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *TableViewCEll =#"TableViewCell";
UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:TableViewCEll forIndexPath:indexPath];
if (Cell == nil) {
Cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableViewCEll];
}
UIImageView *imageView=[[UIImageView alloc]init];
imageView.frame =CGRectMake(5, 5, 100,110);
[Cell.contentView addSubview:imageView];
NSArray * array =[[self.ListOfCarArray objectAtIndex:indexPath.row]objectForKey:#"CarImage"];
if (array.count >0) {
NSString * str = [NSString stringWithFormat:#"%#uploads/Car/%#",[self.GetUserConfiDict objectForKey:#"server"],[[array objectAtIndex:0]objectForKey:#"name"]];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];
manager.responseSerializer = [AFImageResponseSerializer serializer];
[manager GET:str
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
imageView.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error %#.",[error localizedFailureReason]);
}];
}
UILabel * ModelLbl =[[UILabel alloc]initWithFrame:CGRectMake(120, 10, 120, 25)];
ModelLbl.textColor = [UIColor whiteColor];
NSDictionary *str = [[NSDictionary alloc]init];
str =[[self.ListOfCarArray objectAtIndex:indexPath.row]objectForKey:#"Car"];
ModelLbl.text = [str objectForKey:#"model"];
[Cell.contentView addSubview:ModelLbl];
int x = 120;
int y = 50;
for (int i = 1; i<=5; i++) {
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(x, y, 84,15)];
label.textColor = [UIColor whiteColor];
if (i ==1) {
id null = [str objectForKey:#"year"];
if ([null isKindOfClass:[NSNull class]]) {
label.text =#"";
}
else{
label.text = [str objectForKey:#"year"];
[Cell.contentView addSubview:label];
}
}
else if (i == 2){
id null = [str objectForKey:#"color"];
if ([null isKindOfClass:[NSNull class]]) {
label.text =#"";
}
else{
label.text =[str objectForKey:#"color"];
[Cell.contentView addSubview:label];
}
}
else if (i == 3){
id null = [str objectForKey:#"price"];
if ([null isKindOfClass:[NSNull class]]) {
label.text =#"";
}
else{
label.text =[str objectForKey:#"price"];
[Cell.contentView addSubview:label];
x+=100;
y = 30;
}
}
else if (i ==4) {
id null = [str objectForKey:#"miles"];
if ([null isKindOfClass:[NSNull class]]) {
label.text =#"";
}
else{
label.text =[str objectForKey:#"miles"];
[Cell.contentView addSubview:label];
}
}
else if (i == 5){
id null = [str objectForKey:#"stock_number"];
if ([null isKindOfClass:[NSNull class]]) {
label.text =#"";
}
else{
label.text =[str objectForKey:#"stock_number"];
[Cell.contentView addSubview:label];
}
}
y+=20;
}
return Cell;
}
i got my answer and this is what i was searching for..
for (UILabel *lbl in cell.contentView.subviews)
{
if ([lbl isKindOfClass:[UILabel class]])
{
[lbl removeFromSuperview];
}
}
Yes, this is caused by the reuse of the table view cell. It is not only the labels but also the imageView. You are adding the imageView with this method
[Cell.contentView addSubview:imageView];
every time, while it should only be done when the cell is created, i.e. inside the
if (Cell == nil) {
Cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableViewCEll];
}
I'd advise to use a custom UITableViewCell subclass, but if you stick with the current approach, I'd do it this way:
static int IMAGE_VIEW_TAG = 1;
if (Cell == nil) {
Cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableViewCEll];
UIImageView *imageView = [[UIImageView alloc]init];
imageView.frame = CGRectMake(5, 5, 100,110);
imageView.tag = IMAGE_VIEW_TAG;
[Cell.contentView addSubview:imageView];
}
Further below, you can refer to the imageView by the tag:
((UIImageView *)[Cell.contentView viewWithTag:IMAGE_VIEW_TAG]).image = responseObject;
You'll have to do the same for the labels.

TableView isn't updating data even though it recognizes input?

So I have 5 rows and on selection they pass an integer with the row number to my second view controller.
Each number has its own array with items and should then return the amount of items for the row specified.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MasterCell";
MasterCell *cell = (MasterCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (radInt == 0) {
cell.textLabel.text = #"LM";
NSLog(#"My return should have been LM");
}
if (radInt == 1) {
cell.textLabel.text = #"Restauranger";
NSLog(#"My return should have been Rest");
}
if (radInt == 2) {
cell.textLabel.text = [shoppingArray objectAtIndex:indexPath.row];
}
if (radInt == 3) {
cell.textLabel.text = [annatArray objectAtIndex:indexPath.row];
}
//cell.textLabel.text = [listData objectAtIndex:[indexPath row]];
cell.imageView.image = [UIImage imageNamed:#"tab-icon1.png"];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
This is my code just to test it out and it doesn't work. NSLOG works correctly but the data simply wount update... What have I done wrong? It Nslogs LM every time but it also has 1 in the log which is the selected row (radInt).
New approach
static NSString *CellIdentifier = #"MasterCell";
MasterCell *cell = (MasterCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
cell = [[MasterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if (radInt == 0) {
cell.textLabel.text = #"LM";
NSLog(#"My return should have been LM");
}
else if (radInt == 1) {
cell.textLabel.text = #"Restauranger";
NSLog(#"My return should have been Rest");
}
else if (radInt == 2) {
cell.textLabel.text = [shoppingArray objectAtIndex:indexPath.row];
}
else if (radInt == 3) {
cell.textLabel.text = [annatArray objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = #"Noes";
}
//cell.textLabel.text = [listData objectAtIndex:[indexPath row]];
cell.imageView.image = [UIImage imageNamed:#"tab-icon1.png"];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
The view before ----
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SecondViewController *enjoy = [[SecondViewController alloc] init];
if ([[array objectAtIndex:indexPath.row] isEqual:#"Livsmedel"]) {
[enjoy setTitle:[array objectAtIndex:indexPath.row]];
enjoy.radInt = 0;
NSLog(#"0");
}
if ([[array objectAtIndex:indexPath.row] isEqual:#"Restauranger"]) {
[enjoy setTitle:[array objectAtIndex:indexPath.row]];
enjoy.radInt = 1;
NSLog(#"1");
}
if ([[array objectAtIndex:indexPath.row] isEqual:#"Shopping"]) {
[enjoy setTitle:[array objectAtIndex:indexPath.row]];
enjoy.radInt = 2;
}
if ([[array objectAtIndex:indexPath.row] isEqual:#"Annat"]) {
enjoy.radInt = 3;
}
[self performSegueWithIdentifier:#"main" sender:self];
}
You don't actually need to implement didSelectRowAtIndexPath: if you connect the segue in the storyboard from the cell to the next controller. What you need to implement is prepareForSegue:. Your code should look something like this:
- (void)prepareForSegue:(UIStoryboardSegue *) segue sender:(id) sender
{
NSInteger row = [self.tableView indexPathForSelectedRow].row;
SecondViewController *enjoy = segue.destinationViewController;
if ([[array objectAtIndex:row] isEqual:#"Livsmedel"]) {
[enjoy setTitle:[array objectAtIndex:row]];
enjoy.radInt = 0;
NSLog(#"0");
}
if ([[array objectAtIndex:row] isEqual:#"Restauranger"]) {
[enjoy setTitle:[array objectAtIndex:row]];
enjoy.radInt = 1;
NSLog(#"1");
}
if ([[array objectAtIndex:row] isEqual:#"Shopping"]) {
[enjoy setTitle:[array objectAtIndex:row]];
enjoy.radInt = 2;
}
if ([[array objectAtIndex:row] isEqual:#"Annat"]) {
enjoy.radInt = 3;
}
}

UITableView cells take content from others cells

My UITableView cells take content (images) from others cells. I have no idea why that happening, but I am sure that my mistake is silly. At the image below you can see how it looks. Cells on the top take images from the cells on the bottom (facebook and twitter icons).
Here is my code for cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dictionary = [mainArray objectAtIndex:indexPath.section];
NSArray *array1 = [dictionary objectForKey:#"stuff"];
NSString *cellValue = [array1 objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue; // загаловок клетки
cell.textLabel.font = [UIFont fontWithName:#"TrebuchetMS-Bold" size:16];
cell.textLabel.textColor = [UIColor colorWithRed:145/256.0 green:0/256.0 blue:0/256.0 alpha:1.0];
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.textAlignment = UITextAlignmentLeft;
if (indexPath.section == 0 && indexPath.row == 1)
{
if([[NSUserDefaults standardUserDefaults]boolForKey:#"password"] == YES)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
}
switch(indexPath.section)
{
case 2:
{
cell.textLabel.textAlignment = UITextAlignmentCenter;
}
break;
case 3:
{
if (indexPath.row == 0)
cell.imageView.image = [UIImage imageNamed:#"facebook"];
else if (indexPath.row == 1)
cell.imageView.image = [UIImage imageNamed:#"twitter"];
else if (indexPath.row == 2)
cell.imageView.image = [UIImage imageNamed:#"youtube"];
else
cell.imageView.image = [UIImage imageNamed:#"vk"];
}
break;
default:
break;
}
return cell;
}
How can I fix it ?
Cells are reused, so you have to set the imageView of your cells to nil whenever you don't want an image to appear. Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dictionary = [mainArray objectAtIndex:indexPath.section];
NSArray *array1 = [dictionary objectForKey:#"stuff"];
NSString *cellValue = [array1 objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue; // загаловок клетки
cell.textLabel.font = [UIFont fontWithName:#"TrebuchetMS-Bold" size:16];
cell.textLabel.textColor = [UIColor colorWithRed:145/256.0 green:0/256.0 blue:0/256.0 alpha:1.0];
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.textAlignment = UITextAlignmentLeft;
cell.imageView.image = nil;
if (indexPath.section == 0 && indexPath.row == 1)
{
if([[NSUserDefaults standardUserDefaults]boolForKey:#"password"] == YES)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
}
switch(indexPath.section)
{
case 2:
{
cell.textLabel.textAlignment = UITextAlignmentCenter;
}
break;
case 3:
{
if (indexPath.row == 0)
cell.imageView.image = [UIImage imageNamed:#"facebook"];
else if (indexPath.row == 1)
cell.imageView.image = [UIImage imageNamed:#"twitter"];
else if (indexPath.row == 2)
cell.imageView.image = [UIImage imageNamed:#"youtube"];
else
cell.imageView.image = [UIImage imageNamed:#"vk"];
}
break;
default:
break;
}
return cell;
}

Can anyone tell me why tableview data are not displaying until scroll?

In my tableview i have set xml data to display but until scroll it does not display all value. I have reloaded the tableview when i am getting my xml data. I also used [cell.contenView viewWithTag:tagnumber]; But still now its not Working...please help me anybody....
Data are coming and using NSLog i can get the value but not display until scroll.
One think i have to mention that i can see the my cellview and imageview but not showing lable data.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
//cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
// THIS IS A VIEW ABOVE MY CELL NAME: cellView
cellView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,290, 120)] autorelease];
cellView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"order_description_bg.png"]];
cellView.tag =10;
// THIS IS A IMAGEVIEW ABOVE MY cellView NAME: imgView
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, 39, 36)];
imgView.image = [UIImage imageNamed:#"order_image.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 0.0f;
imgView.tag = 5;
// THIS IS A LABEL ABOVE MY cellView NAME: statusLabel
CGRect statusRect = CGRectMake(65, 0, 190, 18);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor greenColor];
statusLabel.tag = 1;
[cell.contentView addSubview:cellView];
[cellView addSubview:statusLabel];
[cellView addSubview:imgView];
}
// [cell.contentView superview];
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(searching == YES && x<=inumOfRowAfterSearch){
NSLog(#"[[searchData objectAtIndex:m] intValue] is : %d",[[searchData objectAtIndex:inumOfRowAfterSearch] intValue]);
y = [[searchData objectAtIndex:inumOfRowAfterSearch] intValue];
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(pendingOrder == NO && todaysOrder == NO && x<=inumOfRowAfterSearch){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
else if(pendingOrder == YES && todaysOrder == NO && x<=inumOfRowAfterSearch){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
}
else{
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(pendingOrder == NO && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
NSLog(#"status lable value: %#",statusLabel.text);
}
else if(pendingOrder == YES && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
}
}
return cell;
}
Before scroll the table.
After Scroll the tableview
Following codes are not necessary in each condition , since you have written the code outside of the condition. It seems duplicate.
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
And coming to your question, it seems initially it skips both if and else if conditions. Comment also the NSLogs and write NSLog in else part of the conditions.
Edit:
// [cell.contentView superview];
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(searching == YES && x<=inumOfRowAfterSearch){
NSLog(#"[[searchData objectAtIndex:m] intValue] is : %d",[[searchData objectAtIndex:inumOfRowAfterSearch] intValue]);
y = [[searchData objectAtIndex:inumOfRowAfterSearch] intValue];
if(pendingOrder == NO && todaysOrder == NO ){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
else if(pendingOrder == YES && todaysOrder == NO ){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
else
{
statusLabel.text = [NSString stringWithFormat:#"Status: None"];
}
}
else{
if(pendingOrder == NO && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
NSLog(#"status lable value: %#",statusLabel.text);
}
else if(pendingOrder == YES && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
}
else
{
statusLabel.text = [NSString stringWithFormat:#"Status: None"];
}
}
return cell;

Set switch to On, reload table then insert a new row

I've got an UITableViewController that I use to create settings of my application.
There is a section with only one row where I put an UISwitch.
How can I insert a new row inside the same section of row with the switch only if the switch in set to YES? And how can I delete this row if the switch is set to NO?
Can anyone help me? Thanks!
I tried to use insertRowsAtIndexPaths:withRowAnimation: method but doesn't work...
This is my settings table code:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = NSLocalizedString(#"Impostazioni", #"");
}
- (void)viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
-(void)addCellToSetCode:(id)sender {
if ([codeSwitch isOn]) {
NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
[[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:#"stateOfSwitch"];
}
else {
NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
[[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:#"stateOfSwitch"];
}
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 4;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section == 0) {
return NSLocalizedString(#"ListaDesideri", #"");
}
if (section == 1) {
return NSLocalizedString(#"CondivisioneMail", #"");
}
if (section == 2) {
return #"Sicurezza";
}
else {
return nil;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) || (section == 2) || (section == 3) {
return 2;
}
else if (section == 1) {
return 1;
}
else {
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.section == 0 && indexPath.row == 0) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
cell.textLabel.text = NSLocalizedString(#"Ordine", #"");
if ([[defaults objectForKey:#"ordinaPer"] isEqualToString:#"Nome"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Nome", #"");
}
if ([[defaults objectForKey:#"ordinaPer"] isEqualToString:#"Costo"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Costo", #"");
}
if ([[defaults objectForKey:#"ordinaPer"] isEqualToString:#"Categoria"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Categoria", #"");
}
if ([[defaults objectForKey:#"ordinaPer"] isEqualToString:#"Nome Discendente"]) {
cell.detailTextLabel.text = NSLocalizedString(#"NomeDiscendente", #"");
}
if ([[defaults objectForKey:#"ordinaPer"] isEqualToString:#"Costo Discendente"]) {
cell.detailTextLabel.text = NSLocalizedString(#"CostoDiscendente", #"");
}
if ([[defaults objectForKey:#"ordinaPer"] isEqualToString:#"Categoria Discndente"]) {
cell.detailTextLabel.text = NSLocalizedString(#"CategoriaDiscendente", #"");
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 0 && indexPath.row == 1) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
cell.textLabel.text = NSLocalizedString(#"DettagliDesiderio", #"");
if ([[defaults objectForKey:#"dettagliView"] isEqualToString:#"costoView"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Costo", #"");
}
if ([[defaults objectForKey:#"dettagliView"] isEqualToString:#"descrizioneView"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Descrizione", #"");
}
if ([[defaults objectForKey:#"dettagliView"] isEqualToString:#"urlView"]) {
cell.detailTextLabel.text = NSLocalizedString(#"URL", #"");
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 1 && indexPath.row == 0) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
cell.textLabel.text = NSLocalizedString(#"Shortener", #"");
if ([[defaults objectForKey:#"linkShortener"] isEqualToString:#"Nessuno"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Nessuno", #"");
}
if ([[defaults objectForKey:#"linkShortener"] isEqualToString:#"is.gd"]) {
cell.detailTextLabel.text = NSLocalizedString(#"is.gd", #"");
}
if ([[defaults objectForKey:#"linkShortener"] isEqualToString:#"bit.ly"]) {
cell.detailTextLabel.text = NSLocalizedString(#"bit.ly", #"");
}
if ([[defaults objectForKey:#"linkShortener"] isEqualToString:#"TinyURL"]) {
cell.detailTextLabel.text = NSLocalizedString(#"TinyURL", #"");
}
if ([[defaults objectForKey:#"linkShortener"] isEqualToString:#"Linkyy"]) {
cell.detailTextLabel.text = NSLocalizedString(#"Linkyy", #"");
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 2 && indexPath.row == 0) {
cell.textLabel.text = #"Access Code";
codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
cell.accessoryView = codeSwitch;
[codeSwitch addTarget:self action:#selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"codeSwitchState"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (indexPath.section == 3 && indexPath.row == 0) {
cell.textLabel.text = NSLocalizedString(#"Supporto", #"");
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 3 && indexPath.row == 1) {
cell.textLabel.text = NSLocalizedString(#"Informazioni", #"");
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
EDIT: Updates below...
I solved part of this problem!
I tried to use [self.tableView reloadData] but doesn't work and casually I solved using [self.tableView setNeedsDisplay]...
Now the switch works but if I set to On it and then I go out from app, completely closing it, the switch doesn't work... How can I solve this?
If this can help other, these are pieces of code updated:
-(void)addCellToSetCode:(id)sender {
if ([codeSwitch isOn]) {
NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
[self.tableView setNeedsDisplay];
[[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:#"codeSwitchState"];
}
else {
NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
[self.tableView setNeedsDisplay];
[[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:#"codeSwitchState"];
}
}
// tableView:numberOfRowsInSection:
else if (section == 2) {
return codeSwitch.on ? 2 : 1;
}
// tableView:cellForRowAtIndexPath:
if (indexPath.section == 2 && indexPath.row == 0) {
cell.textLabel.text = #"Access Code";
codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
cell.accessoryView = codeSwitch;
[codeSwitch addTarget:self action:#selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"codeSwitchState"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (indexPath.section == 2 && indexPath.row == 1) {
if ([codeSwitch isOn]) {
cell.textLabel.text = #"Set Access Code";
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
At least part of your problem (in the updated code) is that you don't create the UISwitch until you create the cell. Your codeSwitch ivar may end up pointing to a different switch as that table row comes in and out of view.
Here's how I'd do this: in tableView:numberOfRowsInSection:, use the NSUserDefaults to see which state the table should be in, instead of using the state of the switch (which may not exist yet). Then, in the switch's action method, call setBool:forKey: for the user defaults before you insert or delete the table row.
In essence, this makes the code follow the MVC model better, because it separates your view (the UISwitch) from the model (the BOOL in user defaults), with the controller (the view controller) in the middle. By confounding the view and the model (the switch and the boolean state), you end up with problems when trying to deal with the state when the view isn't available yet.
BTW, you shouldn't need to call setNeedsDisplay on the table view at all.