Search code examples
iosalignmentcell

How can I align 2 values Left and Right within the one cell?


I need some help with the below. I would like p.no to align to the left of the cell and p.name to align to the right. Any advice?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateStyle:NSDateFormatterShortStyle];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    President *p = (President *)[self.importedRows objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", p.no , p.name];


    return cell;
}

Solution

  • Follow These Steps:
    1. drag & drop 2 labels on your prototypeCell in storyboard at the positions you want them to be in.
    2. Create a subclass of UITableViewCell class in your project.
    3. Assign newly created subClass as class for your table cell from identity inspector.
    4. connect both label outlets with customTableviewcell.h
    5. Import customTableViewCell.h in tableViewController.
    6. Now in (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method, replace code like this

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateStyle:NSDateFormatterShortStyle];
    
        customTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
    
        // Configure the cell...
        President *p = (President *)[self.importedRows objectAtIndex:indexPath.row];
        cell.label1.text = [NSString stringWithFormat:@"%@ , p.no ];
    
        cell.label2.text = [NSString stringWithFormat:@"%@ , p.name ];
    
        return cell;
    }
    

    Let me know if any issues are there :)