Increasing Label Values Separately for Each Row Within a UITableView Section

Working with UITableView Sections and Rows: Increasing Label Values Separately

In this article, we will delve into the world of UITableView sections and rows. Specifically, we’ll explore how to increase label values separately for each row within a section. This is achieved by using a combination of custom cells, actions, and event handling.

Understanding UITableView Structure

A UITableView consists of sections and rows. Each section represents a group of related data, while each row represents an individual item within that section. When you select a cell in the table view, it can trigger various actions based on your specific requirements.

The Code

We’ll use the provided code snippet as a starting point for our implementation. The code is written in Objective-C and utilizes UIKit framework components.

SectionIndexTitlesForTableView Method

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSArray *toBeReturned = [NSArray arrayWithArray:
                             [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z"
                              componentsSeparatedByString:@"|"]];

    return toBeReturned;
}

This method returns an array of section titles for the table view. In this case, we have a single section with 32 titles.

Cell For Row Method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    LocationsCustomCell *cell = (LocationsCustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"LocationsCustomCell" owner:self options:nil];
        cell = locationCustomcell;
    }
    @try {
        if(indexPath.section < [arrayOfCharacters count]) {
            NSString *sortedStr = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

            if([sortedStr isKindOfClass:[NSNull class]]) {
                cell.locationNameLabel.text=@"";
            } else {
                cell.locationNameLabel.text=sortedStr;
                cell.locationNameLabel.textColor=[UIColor blackColor];
            }
        }
    }
    @catch (NSException *exception) {
        
    }
    sectionNo = indexPath.section;

     cell.plusButn.tag = sectionNo*100+indexPath.row;
     cell.minusButn.tag = sectionNo*100+indexPath.row;
     cell.locationCountLabel.tag=sectionNo*100+indexPath.row;

    [cell.plusButn addTarget:self action:@selector(plusButnPressed:) forControlEvents:UIControlEventValueChanged];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; // Set selection style to none
    return cell;
}

This method returns a custom UITableViewCell instance. The cell is reused from the table view’s pool, and its properties are updated based on the row index path.

plusButnPressed Method

- (void)plusButnPressed:(id)sender {
    // Get the current row index path
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[sender locationInView:self.tableView]];
    
    // Increment the label value
    int a = [self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text.intValue;
    a++;
    
    // Update the label text
    [self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text = [NSString stringWithFormat:@"%d",a];
}

This method is called when the plusButn button is pressed. It retrieves the current row index path and increments the label value by 1.

minusButtonPressed Method

- (void)minusButtonPressed:(id)sender {
    // Get the current row index path
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[sender locationInView:self.tableView]];
    
    // Decrement the label value
    int a = [self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text.intValue;
    a--;
    
    // Update the label text
    [self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text = [NSString stringWithFormat:@"%d",a];
}

This method is called when the minusButn button is pressed. It retrieves the current row index path and decrements the label value by 1.

The Solution

To increase label values separately for each row within a section, we need to add two actions to the buttons in our custom cell: plusButtonPressed and minusButtonPressed. We then handle these events in the view controller’s implementation file.

// In ViewController.m

- (void)buttonPressed:(id)sender withEvent:(UIEvent *)event {
    UITouch *touch = [[event touches] anyObject];
    CGPoint location = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];

    // Get the current row index path
    int a = [[self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text intValue];
    
    if ([sender isEqual:cell.plusButn]) {
        a++;
    } else if ([sender isEqual:cell.minusButn]) {
        a--;
    }
    
    [self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text = [NSString stringWithFormat:@"%d",a];
}

The Final Code

// In ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    // Create and configure the table view
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.tableView registerClass:[LocationsCustomCell class] forCellReuseIdentifier:@"LocationsCustomCell"];
    [self.tableView reloadData];

    // Add actions to the buttons in our custom cell
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"LocationsCustomCell" owner:self options:nil];
        cell = locationCustomcell;
        [cell.plusButn addTarget:self action:@selector(plusButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [cell.minusButn addTarget:self action:@selector(minusButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)buttonPressed:(id)sender withEvent:(UIEvent *)event {
    UITouch *touch = [[event touches] anyObject];
    CGPoint location = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];

    // Get the current row index path
    int a = [[self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text intValue];
    
    if ([sender isEqual:cell.plusButn]) {
        a++;
    } else if ([sender isEqual:cell.minusButn]) {
        a--;
    }
    
    [self.tableView cellForRowAtIndexPath:indexPath].locationCountLabel.text = [NSString stringWithFormat:@"%d",a];
}

By using this approach, you can increase label values separately for each row within a section in your UITableView.


Last modified on 2024-04-04