Search code examples
xcodeviewforeachaddsubview

Adding multiple the samve views


I searched the net and books, for an answer but didn't find it. (maybe because I searched the wrong way, or everyone knew the answer to it, except me)

So my problem is like this: I have a view (made in Interface builder) because I know I will need more views that looks the same. I know how to add 1 view, (or more), but the problem is, I don't know how much products there will be in the database. So for each product, I would need to add another view, with different data. The only problem now, How can I add those multiple views?

If there would always be 5 products, I could just do it like this:

ProductController *productfirstController;
ProductController *productsecondController;
...
[scrollview addSubview:productfirstController.view];
[scrollview addSubview:productsecondController.view];
...

But like you see, this it's a horrible way of programming.

My first thought was if I could use a string like this: (the iInt is an integer in a for lus, on the end it add up with 1)

NSString *productController = "productController%d',iInt;

But here I couldn't get further.

does someone has an idea how I could solve this problem?

Thanks in advance!


Solution

  • Instead of using individual variables for the views, use an NSArray. Use a loop to add them to the NSArray and scrollview. Here it is in detail:

    NSArray *productViews = [[NSArray alloc] init];
    
    ProductController *productController;
    for (...) {
        productController = [[ProductController alloc] init...];
    
        [scrollview addSubview:productfirstController.view];
        [productViews addObject:productfirstController];
        [productController release];
    }