我循环遍历一个数组并添加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];
}
答案 0 :(得分: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;
}
}