Chris
Chris

Reputation: 1034

UIButtons & UILabels inside a tableviewcell

I have two UIButtons and some labels inside a table view cell. I have 2 sections, the first section contains one table view cell and inside of that cell there are two UIButtons that call on an api to fetch new data for the cells in section 2. In a certain if case, a label is created because the string is very long so I have to create a new frame for the cell.

The problem that I am currently having is that the button text also gets update with new information and sometimes the string is short or sometimes the string is long, so I have to remove the button and a add a new button with a new frame to fit the new string. But if the past button string was shorter than the new one, the button still appears in the background. I tried removing it from the superview and also checking that it has removed from the superview (check that it is null once I remove it) and it is, but it still appears on the screen. The same thing happens with the UILabels as well. I also tried to removing them from super view with a tag (viewWithTag:123). Anyone have any pointers, ideas, suggestions, anything really, that could help me figure/fix this out?

-(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];
        UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
        selectedBackgroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
        cell.selectedBackgroundView = selectedBackgroundView;

        if(cell==nil) { NSLog(@"Cell is still nil");}
    }
    cell.textLabel.text = nil;
    cell.accessoryView = nil;
    cell.detailTextLabel.text = nil;
    cell.userInteractionEnabled = YES;

    if(indexPath.section == 0)
    {

            dosageButton                            = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            amountButton                            = [UIButton buttonWithType:UIButtonTypeRoundedRect];

            [dosageButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            [dosageButton setContentEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
            [amountButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            [amountButton setContentEdgeInsets:UIEdgeInsetsMake(0, 15.5, 0, 0)];


            if(strengths.count == 0) { [dosageButton setTitle:@"Dosage" forState:UIControlStateNormal];}
            else
            {

                [dosageButton setTitle:selectedStrength forState:UIControlStateNormal];
                CGSize stringsize = [selectedStrength sizeWithFont:[UIFont systemFontOfSize:14]];
                [dosageButton setFrame:CGRectMake(5, 27.5, stringsize.width + 30, 30)];
            }

            if(quantity.count == 0) { [amountButton setTitle:@"Amount" forState:UIControlStateNormal];}
            else
            {

                int value = [selectedQuantity intValue];
                if (value == 1)
                {
                    NSString *amountAndFormat = [NSString stringWithFormat:@"%@ %@", selectedQuantity, selectedFormat];
                    [amountButton setTitle:amountAndFormat forState:UIControlStateNormal];
                    CGSize stringsize = [selectedStrength sizeWithFont:[UIFont systemFontOfSize:14]];
                    CGSize amountSize = [amountAndFormat sizeWithFont:[UIFont systemFontOfSize:14]];

                    if(amountSize.width+stringsize.width > 250)
                    {
                        dosageButton.frame                      = CGRectMake(5, 27.5, 130, 30);
                        amountButton.frame                      = CGRectMake(140, 27.5, 160, 30);
                    }
                    else
                    {
                        [amountButton setFrame:CGRectMake(stringsize.width + 40, 27.5, amountSize.width + (amountSize.height * 2.1), 30)];
                    }
                }
                else
                {
                    NSString *amountAndFormat = [NSString stringWithFormat:@"%@ %@", selectedQuantity, selectedFormatPlural];
                    [amountButton setTitle:amountAndFormat forState:UIControlStateNormal];
                    CGSize stringsize = [selectedStrength sizeWithFont:[UIFont systemFontOfSize:14]];
                    CGSize amountSize = [amountAndFormat sizeWithFont:[UIFont systemFontOfSize:14]];
                    if(amountSize.width + stringsize.width> 250)
                    {
                        dosageButton.frame                      = CGRectMake(5, 27.5, 130, 30);
                        amountButton.frame                      = CGRectMake(140, 27.5, 160, 30);
                    }
                    else
                    {
                        [amountButton setFrame:CGRectMake(stringsize.width + 40, 27.5, amountSize.width + (amountSize.height * 2.1), 30)];
                    }
                }

            }

            [dosageButton addTarget:self action:@selector(showDosages:) forControlEvents:UIControlEventTouchUpInside];
            [amountButton addTarget:self action:@selector(showAmount:) forControlEvents:UIControlEventTouchUpInside];

            //[cell.contentView addSubview:dosageButton];
            //[cell.contentView addSubview:amountButton];
            //adding it to view instead of cell because of userInteraction.
            //if I add it to cell.contentView and userInteractionEnabled = NO
            //then the user can't press the button
            //but if the it is enabled then they can click the cell and looks tacky!

            [self.view addSubview:dosageButton];
            [self.view addSubview:amountButton];
            cell.userInteractionEnabled = NO;
    }

    if(indexPath.section == 1)
        {
            if(localName.count == 0)
            {
                //Nothing
            }

            else
            {
            CGRect longStringFrame = CGRectMake(12, 4, 250, 120);
            //UILabel *longStringLabel = [[UILabel alloc] initWithFrame:longStringFrame];
            UILabel *longStringLabel = [[UILabel alloc] initWithFrame:longStringFrame];
            longStringLabel.backgroundColor = [UIColor clearColor];
            longStringLabel.font = [UIFont systemFontOfSize:12];
            longStringLabel.text = [NSString stringWithFormat:@"Something super duper long. Some really really long string that has a lot of information and cannot fit in one line so I have to use numberOfLines = 0 and NSLineBreakByWordWrapping. This string is really really really long.]];
            longStringLabel.textColor = [UIColor blackColor];
            longStringLabel.numberOfLines = 0;
            longStringLabel.lineBreakMode = NSLineBreakByWordWrapping;
            cell.textLabel.text = @"";
            longStringLabel.tag = 123;
            [cell.contentView addSubview:longStringLabel];
            }
        }


}



- (void) showDosages:(UIButton *)sender
{
    [dosageButton removeFromSuperview];
    [amountButton removeFromSuperview];
    [[cell.contentView viewWithTag:123] removeFromSuperview];
    NSLog(@"%@",[dosageButton superview]);
    NSLog(@"%@",[amountButton superview]);


    //Also tried it this way as well. Didn't work
    //[dosageButton performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
    //[amountButton performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];

    dispatch_async(someDispatch, ^{ NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat: @"http://somewebsite.com"]]]; [self performSelectorOnMainThread:@selector(fetchData:) withObject:data waitUntilDone:YES]; });
}

showAmount is similar to showDosages

Upvotes: 0

Views: 611

Answers (2)

Jay Gajjar
Jay Gajjar

Reputation: 2741

Here is the simple example of multiple cell identifier hope it might help

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";

if(flag == 0) {

   MainArticleTableViewCell *cell = (MainArticleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

   if (cell == nil) {
       cell = [[[MainArticleTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier1] autorelease];
   }

   cell.textLabel.text= @"Cell1";

   return cell;
}
else {
   NewsTableViewCell *cell = (NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

   if (cell == nil) {
       cell = [[[NewsTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier2 orientation:currentOrientation] autorelease];

   }

   cell.textLabel.text= @"Cell1";

   return cell;
}

return nil;
}

Upvotes: 0

Jay Gajjar
Jay Gajjar

Reputation: 2741

I would suggest you to create a custom cell put all the labels & buttons you want, give an iboutles so that you can easily manage things.

Custom cell tutorial http://mobile.tutsplus.com/tutorials/iphone/customizing-uitableview-cell/

Once you made your cell you can set the height of cell according to your string. Your buttons will automatically adjusted when your cell size is increased or decreased

Upvotes: 1

Related Questions