Ollie Hirst
Ollie Hirst

Reputation: 592

Dynamically created UIView Objects

I have a predicament, in as much that I need to create an arbitrary amount of UIView Objects. I have an NSArray and what I need to do is create UIView Objects for the number of items in the array, so I got an int from the [NSArray count]; method, so I know the number of objects needing creating, but the way to implement this has me stumped. I'll include some psudocode below to attempt to give across what I need to do:

[UIView returnMultipleUIViewsForInt:[theArray count]];

Obviously that won't work, but some way of creating an arbitrary amount of objects at runtime, which I can work with would be good.

So in short:

I need to create a certain number of UIViews based upon the number of items in an array. I then need to access each view that is created and use it as a regularly created view might be used, doing things like adding one of them as a subview to a different view.

Upvotes: 2

Views: 1676

Answers (2)

BJ Homer
BJ Homer

Reputation: 49034

NSMutableArray *newViews = [NSMutableArray array];
for (int i=0; i<[theArray count]; ++i) {
    UIView *view = [[UIView alloc] init];
    [newViews addObject:view];
    [view release];
}

Upvotes: 1

Noah Witherspoon
Noah Witherspoon

Reputation: 57149

- (NSArray *)createNumberOfViews:(NSInteger)number
{
    NSMutableArray *viewArray = [NSMutableArray array];
    for(NSInteger i = 0; i < number; i++)
    {
        UIView *view = [[UIView alloc] init];
        // any setup you want to do would go here, e.g.:
        // view.backgroundColor = [UIColor blueColor];
        [viewArray addObject:view];
        [view release];
    }
    return viewArray;
}

Upvotes: 2

Related Questions