9to5ios
9to5ios

Reputation: 5545

Keep Button State Selected in UICollection view with horizontal scroll

I am following this example I have added a button in the view

enter image description here On selection the button image change to Green icon image.

How could I retain it using this example?

Upvotes: 0

Views: 71

Answers (2)

Ramkrishna Sharma
Ramkrishna Sharma

Reputation: 7019

I had updated the existing code of your example to your requirement please find the below url for download the code and review it.

Link : https://www.dropbox.com/s/6xsr4o88khyijun/HorizontalTables.zip?dl=0

Highlight of the code which I had done it.

1) Take the NSMutableArray *arrSelection property in HorizontalTablesAppDelegate class.
2) Fill the data of arrSelection in ArticleListViewController_iPhone class of viewDidLoad method.

    for (NSInteger i = 0; i < [self.articleDictionary.allKeys count]; i++)
    {                        
        HorizontalTableCell_iPhone *cell = [[HorizontalTableCell_iPhone alloc] initWithFrame:CGRectMake(0, 0, 320, 416) tag:i];

        categoryName = [sortedCategories objectAtIndex:i];
        currentCategory = [self.articleDictionary objectForKey:categoryName];
        cell.articles = [NSArray arrayWithArray:currentCategory];

        if(i == 0)
            appDelegate.arrSelection = [[NSMutableArray alloc] init];

        NSMutableArray *arrSubData = [[NSMutableArray alloc] init];

        for(NSInteger j=0; j<currentCategory.count; j++)
            [arrSubData addObject:[NSNumber numberWithBool:NO]];

        [appDelegate.arrSelection addObject:arrSubData];
        [arrSubData release];

        [self.reusableCells addObject:cell];
        [cell release];
    }

3) On HorizontalTableCell_iPhone class of cellForRowAtIndexPath method

NSMutableArray *arrSelectionInfo = appDelegate.arrSelection[tableView.tag];
BOOL isSelect = [arrSelectionInfo[indexPath.row] boolValue];

if(isSelect)
    [cell.btnSelection setBackgroundColor:[UIColor greenColor]];
else
    [cell.btnSelection setBackgroundColor:[UIColor whiteColor]];

And didSelectRowAtIndexPath method

NSMutableArray *arrUpdate = appDelegate.arrSelection[tableView.tag];
[arrUpdate replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
[tableView reloadData];

Hope this will work for you.

Upvotes: 1

rptwsthi
rptwsthi

Reputation: 10182

To keep button state selected you need to store information of selection on a dictionary for the cell. So once cell is reloaded, you can apply selection setting based on information you have.

There is no direct way (even if there was you should now use that, as it will lead to memory abuse) to keep it selected all the time.

Upvotes: 1

Related Questions