0

我正在根据 for 循环中数组元素的数量将子视图添加到我的滚动视图中。容器视图内部还有一个额外的子视图。问题是只有第一个容器视图包含添加的子视图,而新的容器视图不包含第三个一个也有。我检查了子视图的框架,但似乎仍然不起作用。

CGFloat contentOffset = 0.0f;
//add tej views one by one to scrollview

for (NSString *packageType in packageTypesArray) 
{

    CGRect lvPackageContainerFrame = CGRectMake(contentOffset, 0.0f,scrollView.frame.size.width,scrollView.frame.size.height);

    LVPackageContainer *lvPackageContainer = [[LVPackageContainer alloc] initWithFrame:lvPackageContainerFrame];

    NSLog(@"Frame %@",NSStringFromCGRect(lvPackageContainerFrame));
    lvPackageContainer.packageType = packageType;
    [packageContainersArray addObject:lvPackageContainer];

     UIImageView *backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 264, 314)];
     NSLog(@"BackgroundImage %@",backgroundImage);
     backgroundImage.backgroundColor = [UIColor redColor];
     [backgroundImage setImage:[UIImage imageNamed:@"shadowBackground.png"]];
     backgroundImage.center = lvPackageContainer.center;
     [lvPackageContainer addSubview:backgroundImage];


    [scrollView addSubview:lvPackageContainer];

    contentOffset += lvPackageContainerFrame.size.width;
    scrollView.contentSize = CGSizeMake(contentOffset, scrollView.frame.size.height);

}   
4

1 回答 1

1
backgroundImage.center = CCGPointMake(lvPackageContainerFrame.size.width/2, lvPackageContainerFrame.size.height/2);

如果添加子视图,则坐标系从其父视图开始

在您的情况下,当您为第二个视图设置中心时,它将变成 {480,240} (假设该视图在 iphone 中是全屏)因此,您可以看到的第三个子视图实际上是第 2 页的子视图。

更新:当您获得视图的中心时,它实际上是根据帧值计算的:

center.x = (frame.origin.x + frame.size.width) / 2;
center.y = (frame.origin.y + frame.size.height) / 2;

Therefore assume your second view is with CGRectMake(320, 0, 320, 480), the center of it will be

center.x = (320 + 320) / 2;
center.y = (0 + 480) / 2;

So your subview will be center at {480,240} of the second view.

If you convert it relative to the scrollview, the subview will be at {(320+480),(0+240)}, which you will see it is on the 3rd view, not the 2nd one

于 2012-07-26T10:58:49.977 回答