1

我正在遍历一个数组并添加 UIImageViews,该数组有不同的计数,具体取决于某些东西。所以 UIImageViews 的数量是不同的。我需要做的是在视图中心将它们排成一排。我知道我需要使用我遇到问题的计算的代码。

    for (int i = 0; i < [_lettersArray count]; i++){

    UIImage* imageContainer = [UIImage imageNamed:@"container.png"];
            UIImageView *containerView = [[UIImageView alloc] initWithImage:imageContainer];
            containerView.frame = CGRectMake(???,120,imageContainer.size.width,imageContainer.size.height);
[self.view addSubview:containerView];
}
4

1 回答 1

2
[self _layoutViews:self.imageViews inView:self.view];

- (void) _layoutViews:(NSArray *)views inView:(UIView *)contentView
{
    NSInteger overallWidth = 0;
    for ( UIView *view in views ) {
        overallWidth += view.frame.size.width;
    }

    CGSize contentSize = contentView.frame.size;
    CGFloat startOffset = (contentSize.width - overallWidth)/2.0;
    CGFloat offset = startOffset;
    for ( UIView *view in views ) {
        CGRect frame = view.frame;
        frame.origin.x = offset;
        frame.origin.y = (contentSize.height/2.0) - (frame.size.height/2.0);
        view.frame = frame;
        offset += view.frame.size.width;
    }
}

对于您的示例代码,它将是这样的:

    CGFloat count = [_lettersArray count];
    NSMutableArray *imageViews = [[NSMutableArray alloc] initWithCapacity:count];
    for (int i = 0; i < [_lettersArray count]; i++) {
        UIImage *imageContainer = [UIImage imageNamed:@"container.png"];
        UIImageView *containerView = [[UIImageView alloc] initWithImage:imageContainer];
        containerView.frame = CGRectMake(0,120,imageContainer.size.width,imageContainer.size.height);
        [imageViews addObject:containerView];
        [self.view addSubview:containerView];
    }

    [self _horizontalCenterViews:imageViews inView:self.view];

    return YES;
}

- (void) _horizontalCenterViews:(NSArray *)views inView:(UIView *)contentView
{
    NSInteger overallWidth = 0;
    for ( UIView *view in views ) {
        overallWidth += view.frame.size.width;
    }

    CGSize contentSize = contentView.frame.size;
    CGFloat startOffset = (contentSize.width - overallWidth)/2.0;
    CGFloat offset = startOffset;
    for ( UIView *view in views ) {
        CGRect frame = view.frame;
        frame.origin.x = offset;
        view.frame = frame;
        offset += view.frame.size.width;
    }
}
于 2012-11-19T23:30:24.873 回答