概述
要確保子視圖在父視圖中的相對位置保持不變第二種方法:自動佈局子視圖
示例
先看圖
放大之前
放大之後
我們看到父視圖的四個角和中間位置的子視圖,相對於父視圖的位置沒有發生改變。
示例代碼如下
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
//父視圖
UIView* _superV;
//左上角
UILabel* _label01;
//右上角
UILabel* _label02;
//右下角
UILabel* _label03;
//左下角
UILabel* _label04;
//中間
UIView* _centerV;
}
@end
仔細看代碼註釋
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//創建父視圖
_superV = [UIView new];
_superV.frame = CGRectMake(30, 30, 200, 300);
_superV.backgroundColor = [UIColor blueColor];
//四個角的子視圖
_label01 = [UILabel new];
_label01.frame = CGRectMake(0, 0, 40, 40);
_label01.backgroundColor = [UIColor redColor];
_label01.text = @"01";
_label02 = [UILabel new];
_label02.frame = CGRectMake(200-40, 0, 40, 40);
_label02.backgroundColor = [UIColor redColor];
_label02.text = @"02";
_label03 = [UILabel new];
_label03.frame = CGRectMake(200-40, 300-40, 40, 40);
_label03.backgroundColor = [UIColor redColor];
_label03.text = @"03";
_label04 = [UILabel new];
_label04.frame = CGRectMake(0, 300-40, 40, 40);
_label04.backgroundColor = [UIColor redColor];
_label04.text = @"04";
[_superV addSubview:_label01];
[_superV addSubview:_label02];
[_superV addSubview:_label03];
[_superV addSubview:_label04];
[self.view addSubview:_superV];
//中間的子視圖
_centerV = [UIView new];
_centerV.frame = CGRectMake(0, 0, _superV.bounds.size.width, 40);
_centerV.center = CGPointMake(200/2, 300/2);
_centerV.backgroundColor = [UIColor redColor];
[_superV addSubview:_centerV];
//下面是重點
//視圖的自動佈局屬性
_label02.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
_label03.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin;
_label04.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
_centerV.autoresizingMask = UIViewAutoresizingFlexibleTopMargin
|UIViewAutoresizingFlexibleBottomMargin
|UIViewAutoresizingFlexibleWidth;
}
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//點擊空白處給父視圖添加一個2s的放大動畫
[UIView animateWithDuration:(2) animations:^{
_superV.frame = CGRectMake(30, 30, 340, 500);
}];
}
@end