Search code examples
objective-cuiviewcore-animationalignmentuiviewanimation

How to add UIView subviews in a view aligned like 3x3 table


I have created a main View and in that I add 9 UIMyView that I subclassed from UIView. I add instances of that UIMyViews using NSBundle to load the nib file and addSubview in the main view controller, of course all of these views are appeared in the upper left corner of the super view one hiding the other and the last one to be visible, which either I need to position them somehow using points in super view or create something like a table and add to its cells the UIMyViews?!

Imagine you have a table and put 9 deck cards positioned 3 rows and 3 columns (9 cards). This is what I need to achieve.

[EDIT] Check this image: http://www.wpclipart.com/recreation/games/card_deck/cards_symbols/playing_card_symbols.png

I just need 3 rows and 3 columns.

Anyone can suggest best practice for this kind of operation?

Afterwards just to have in mind I want to implement various animations and effects on these UIMyViews while draged, touched and reordering etc.

Thank you.


Solution

  • If you want to loop through all the views and position them in a grid, you can so like this:

        // Array of 9 views    
    NSArray *views = [NSArray arrayWithObjects:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], nil];
    
    int count = 0;
    int maxPerRow = 3;
    int row = 0;
    float spacing = 100.0;
    
    for(UIView *view in views)
    {
        // Only added to tell the difference between views, make sure to import QuartzCore or remove the next 3 lines
        view.backgroundColor = [UIColor colorWithRed:.5 green:0 blue:0 alpha:1];
        view.layer.borderWidth = 1;
        view.layer.borderColor = [UIColor whiteColor].CGColor;
    
        // position view
        view.frame = CGRectMake(count*spacing, row * spacing, view.frame.size.width, view.frame.size.height);
        [self.view addSubview:view];
    
        if(count % maxPerRow == maxPerRow-1)
        {
            count = 0;
            row++;
        }
        else
        {
            count++;
        }
    }
    

    That will give you something like this:

    enter image description here