How to add button on UITableViewCell

11,338

There is a few ways to add button on UITAbleViewCell:
1) If you are using Storyboards you can create cell prototype with button and than you can access this button with tag property
2) Subclass UITableViewCell and add button on init
3) Add button to cell in tableView:cellForRowAtIndexPath: method

UPD
Here is a tutorial how to customize UITableViewCell with Storyboards

Share:
11,338
Ammad
Author by

Ammad

Updated on June 04, 2022

Comments

  • Ammad
    Ammad almost 2 years

    I have a pre-populated UITableViewCell on which cell have a Label and UITextField. Suppose I have a cell with label "map" and I want to add button on that cell how can I do this?
    I tried but this is not working.
    Here is the code:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"rateSheetCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        if (indexPath.row == 0)
        {
            ((UILabel*)[cell viewWithTag:100]).text = @"Title";
            ((UITextField*)[cell viewWithTag:101]).placeholder = @"Title";
            ((UITextField*)[cell viewWithTag:101]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"resource_title"];
            ((UITextField*)[cell viewWithTag:101]).keyboardType = UIKeyboardTypeDefault;
        }
        else
        {
            if([arrayResourceColumns[indexPath.section][indexPath.row][@"label"] isEqualToString:@"OT ($)"]){
    
                NSInteger desiredLabel = (NSInteger)(arrayResourceColumns[indexPath.section][indexPath.row][@"label"]);
    
                //NSString *desiredLabel = arrayResourceColumns[indexPath.section][indexPath.row][@"label"];
                NSLog(@"Label is>>>>--------%ld", (long)desiredLabel);
    
                if (indexPath.row == desiredLabel ) {
                    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
                    [b setFrame:CGRectMake(0, 0, 50, 50)];
                }
    
    
            }
            ((UILabel*)[cell viewWithTag:100]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"label"];
            ((UITextField*)[cell viewWithTag:101]).placeholder = ((UILabel*)[cell viewWithTag:100]).text;
            ((UITextField*)[cell viewWithTag:101]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"attribute_value"];
    
            if (indexPath.row == [arrayResourceColumns[indexPath.section] count] - 1)
            {
                ((UITextField*)[cell viewWithTag:101]).enabled = NO;
            }
        }
    }