Search code examples
iosuitableviewuiswitch

How to populate UITableView with UISwitch.


I am using Apple's Sample Code TheElements for this question. The project can be found here: TheElements

I would like to know how to populate the "Grouped by State" UITableView using a UISwitch. I have added a UISwitch to the File: AtomicElementFlippedView which will add the selected element to the "Grouped by State" UITableView. Just to clarify I have removed the "Grouped by State" UITableView data. I would like the UITableView to get populated when the user taps the UISwitch to the ON position which will add the selected element into the UITableView.I've done a ton of Googling and it seems there are several ways to go about it, but none seem to work. Any help would be greatly appreciated.

GUI:https://i.sstatic.net/mt1ZI.jpg


Solution

  • If I understand your question correctly, you will need to implement the following methods:

    - (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
    {
        //This should really be a class in its own right. 
        UIView* headerView = [UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 0); 
        UISwitch* aSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
        [headerView addSubView:aSwitch];
    
    }
    
    - (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
    {
        return 80;
    }
    

    What happened?

    We created a UIView container and added a UISwitch to it, returning the UIView as the header view, as per the table view contract.

    The headerView created above should really be created as a class in its own right, and you should override layoutSubviews to put the components in their correct location respective to the parent views size. (This is how to do auto-layout in code).