Reputation: 1085
I have an app right now that has a table view with multiple cells that were loaded from an array. I delimited the text in a text view to separate the text into components that then were added to an array. From there I set the text label of each cell to each component in the array. So I have something that looks like this...
And I want to be able to select a cell and it highlights the cell, then I want to be able to click one of the buttons on the right. When I click a button it takes the text label of that cell and stores it in an array as a component.
I don't know how I would go about writing the code for "take the text label of the selected cell and store it as a component." Is there a way to detect if the cell is selected?
Upvotes: 0
Views: 1344
Reputation: 130193
You'll want to use a NSMutableArray
to achieve this because you can add and remove objects from it on the fly:
- (void)viewDidLoad
{
[super viewDidLoad];
myMutableArray = [[NSMutableArray alloc] init];
}
- (void)myButtonClicked
{
NSMutableArray *myMutableArray;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[self.tableView indexPathForSelectedRow]];
if ([myMutableArray containsObject:cell.textLabel.text]) {
[myMutableArray removeObject:cell.textLabel.text];
}else{
[myMutableArray addObject:cell.textLabel.text];
}
}
Upvotes: 1
Reputation: 18363
An even better approach is to take the text from your array that provides data to the table view and put that in the other array. I'll call them sourceArray
and destinationArray
.
- (IBAction)buttonAction:(id)sender {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *string = [self.sourceArray objectAtIndex:indexPath.row];
[self.destinationArray addObject:string];
}
I suspect though that the indexPathForSelectedRow
method was the one you were looking for. If you still need to go with the label text, modify the handler as shown:
- (IBAction)buttonAction:(id)sender {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *string = selectedCell.textLabel.text;
[self.destinationArray addObject:string];
}
Hope this helps!
Upvotes: 1