Benjamin
Benjamin

Reputation: 663

how to add subviews in a 'for' loop

I'm simply trying to add a UIView for every object in an array without displaying more than 3 on screen but the views aren't next to each other. There is a big gap (one view width) between each view. Here's what I've got;

int numberOfUsersOnScreen;

if (array.count < 3) {
    numberOfViewsOnScreen = array.count;
}else{
    numberOfUsersOnScreen = 3;
}

double width = (self.scrollView.frame.size.width/numberOfViewsOnScreen);
CGRect r = CGRectMake(0, 0, width, 1200);
[self.usersScrollView setContentSize:CGSizeMake(width*array.count, 0)];

for (int i = 0; i < users.count; i++) {  
       r.origin.x = width * i;
       UIView * view = [[UIView alloc] initFrame:r];
       [self.scrollView addSubview:view];
}    

The Orange is the scrollView underneath

Upvotes: 3

Views: 1877

Answers (3)

Maken
Maken

Reputation: 23

for (int i = 0; i < users.count; i++) {  
   r.origin.x = width * i;
   UIView * view = [[UIView alloc] initFrame:r];
   [self.scrollView addSubview:view];
} 

In this way you have also a memory leak on view(s) object

for (int i = 0; i < users.count; i++) {  
   r.origin.x = width * i;
   UIView * view = [[UIView alloc] initFrame:r];
   [self.scrollView addSubview:view];
   [view release]; 
} 

Upvotes: 0

Jaybit
Jaybit

Reputation: 1864

Try this:

int xPosition = 0;
for (int i = 0; i < users.count; i++) {  
   UIView * view = [[UIView alloc] initFrame:CGRectMake(xPosition, 0, width, 1200)];
   [self.scrollView addSubview:view];
   xPosition += width;
}    

Upvotes: 4

Joel Kravets
Joel Kravets

Reputation: 2471

Instead of

[self.scrollView setContentSize:CGSizeMake(width*array.count, 0)];

It should be

[self.scrollView setContentSize:CGSizeMake(width*array.count, self.scrollView.frame.size.height)];

Upvotes: 0

Related Questions