如何在'for'循环中添加子视图

时间:2012-02-07 21:10:13

标签: iphone objective-c ios cocoa-touch ipad

我只是尝试为数组中的每个对象添加一个UIView,而不会在屏幕上显示超过3个但视图不是彼此相邻的。每个视图之间有一个很大的间隙(一个视图宽度)。这就是我所拥有的;

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

3 个答案:

答案 0 :(得分:4)

试试这个:

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;
}    

答案 1 :(得分:0)

而不是

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

应该是

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

答案 2 :(得分:0)

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

通过这种方式,您还可以在视图对象

上发生内存泄漏
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]; 
}