サイズについてはこれを試してみてください!;-)
ViewController.h
#define BUFFER 10
#define WIDTH 90
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) NSMutableArray *ViewArray;
- (IBAction)hideViews:(id)sender;
- (void)centerVisibleViews;
@end
ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize ViewArray;
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *colorArray = [NSMutableArray array];
[colorArray addObject:[UIColor redColor]];
[colorArray addObject:[UIColor orangeColor]];
[colorArray addObject:[UIColor yellowColor]];
[colorArray addObject:[UIColor greenColor]];
[colorArray addObject:[UIColor blueColor]];
[colorArray addObject:[UIColor purpleColor]];
[colorArray addObject:[UIColor blackColor]];
[self setViewArray:[NSMutableArray array]];
for (int i = 0; i < 7; i = i + 1) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(BUFFER + ((WIDTH + BUFFER) * i), BUFFER, WIDTH, WIDTH)];
[view setBackgroundColor:[colorArray objectAtIndex:i]];
[[self ViewArray] addObject:view];
[[self view] addSubview:view];
}
}
- (IBAction)hideViews:(id)sender {
for (int i = 0; i < [[self ViewArray] count]; i = i + 1) {
if (i == 1 || i == 4) {
[(UIView *)[[self ViewArray] objectAtIndex:i] setHidden:YES];
}
}
[self centerVisibleViews];
}
- (void)centerVisibleViews {
int visibleViews = 0;
for (int i = 0; i < [[self ViewArray] count]; i = i + 1) {
if (![(UIView *)[[self ViewArray] objectAtIndex:i] isHidden]) {
visibleViews = visibleViews + 1;
}
}
float totalWidth = (BUFFER * 2) + (WIDTH * [[self ViewArray] count]) + (BUFFER * ([[self ViewArray] count] - 1));
float visibleWidth = (BUFFER * 2) + (WIDTH * visibleViews) + (BUFFER * (visibleViews - 1));
// Make it sexy with an animation!!!
[UIView animateWithDuration:1.0
animations:^{
float offset = (totalWidth - visibleWidth) / 2.0;
for (int i = 0; i < [[self ViewArray] count]; i = i + 1) {
UIView *thisView = [[self ViewArray] objectAtIndex:i];
if (![thisView isHidden]) {
[thisView setFrame:CGRectMake(offset, BUFFER, WIDTH, WIDTH)];
offset = offset + WIDTH + BUFFER;
}
}
}
];
}
@end
メインビューにボタンを追加し、それをに結び付けるだけIBOutlet
です。私のiPadシミュレーターで素敵できれいです。