#import "ViewController.h" #import "MainView.h" @implementation ViewController -(void)viewDidLoad{ MainView* mView = [[MainView alloc] initWithFrame:CGRectMake(40, 100, 200, 300)] ; mView.backgroundColor = [UIColor blueColor] ; [self.view addSubview:mView] ; mView.tag = 1001 ; } -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { static BOOL isBig = YES ; [UIView beginAnimations:nil context:nil] ; [UIView setAnimationDuration:1.0] ; MainView* view = (MainView*)[self.view viewWithTag:1001] ; if (isBig == YES) { view.frame = CGRectMake(0, 0, 320, 480) ; } else { view.frame = CGRectMake(40, 100, 200, 300) ; } [UIView commitAnimations] ; isBig = !isBig ; } @end
#import <UIKit/UIKit.h> @interface MainView : UIView { //定義子視圖對象 UIView* _subView01 ; UIView* _subView02 ; UIView* _subView03 ; UIView* _subView04 ; } @end #import "MainView.h" @implementation MainView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code //父親視圖的背景色:藍色 self.backgroundColor = [UIColor blueColor] ; //建立子視圖對象 _subView01 = [[UIView alloc] init] ; _subView01.frame = CGRectMake(0, 100, 200, 100) ; _subView01.backgroundColor = [UIColor orangeColor] ; _subView02 = [[UIView alloc] init] ; _subView02.frame = CGRectMake(140, 0, 60, 60) ; UIImageView *imgVirw01 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chilli.png"]]; [_subView02 addSubview:imgVirw01]; _subView02.backgroundColor = [UIColor yellowColor] ; _subView03 = [[UIView alloc] init] ; _subView03.frame = CGRectMake(0, 240, 60, 60) ; _subView03.backgroundColor = [UIColor yellowColor] ; UIImageView *imgVirw03 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"egg-plant.png"]]; [_subView03 addSubview:imgVirw03]; _subView04 = [[UIView alloc] init] ; _subView04.frame = CGRectMake(140, 240, 60, 60) ; _subView04.backgroundColor = [UIColor yellowColor]; UIImageView *imgVirw04 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"potato.png"]]; [_subView04 addSubview:imgVirw04]; [self addSubview:_subView01] ; [self addSubview:_subView02] ; [self addSubview:_subView03] ; [self addSubview:_subView04] ; //隱藏其餘三個視圖 // _subView02.hidden = YES ; // _subView03.hidden = YES ; // _subView04.hidden = YES ; //設置自動調整子視圖的屬性 //UIViewAutoresizingFlexibleHeight:自動調整視圖的高度 //UIViewAutoresizingFlexibleWidth:自動調整視圖的寬度 _subView01.autoresizingMask = UIViewAutoresizingFlexibleTopMargin| UIViewAutoresizingFlexibleBottomMargin| UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; _subView02.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin ; _subView03.autoresizingMask = UIViewAutoresizingFlexibleTopMargin| UIViewAutoresizingFlexibleRightMargin ; _subView04.autoresizingMask = UIViewAutoresizingFlexibleTopMargin| UIViewAutoresizingFlexibleLeftMargin ; // UIView* view; } return self; } @end