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