自定義視圖控制
// 我們可以根據空間重復使用的情況,自己封裝一個view,提高代碼的可重用性
1. 創建controller類 繼承于UIViewController
// 新建viewController是MVC設計模式的一種體現(Model負責數據模型 View負責視圖 Controller負責管理 Model和View)
2. 在AppDelegate.m文件中 引入創建的controller類 ,并初始化一個變量 是self.window.rootViewController = 初始化的變量
RootViewController *rootVC = [[RootViewController alloc]init];
self.window.rootViewController = rootVC;
3.創建view類 ,繼承于UIView
4.在創建的view類中,在這個view的.h文件中 聲明 Label Button textField等 在.m文件中對所創建的 Label 或 Button 初始化
FirstView.h文件中
@property(nonatomic,retain)UILabel *myLabel;
FirstView.m文件中
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self p_setUp];
}
return self;
}
- (void)p_setUp{
self.myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 50)];
self.myLabel.backgroundColor = [UIColor blackColor];
[self addSubview:self.myLabel];
}
5. 在第2部創建的controller類的.m文件中引入view類,并在延展中申明一個view的屬性 然后重寫 loadView 方法
@interface RootViewController ()
@property(nonatomic,retain)FirstView *fView;
@end
@implementation RootViewController
// 必須把controller自帶的view 替換成我們自定義的view ,需要在controller.m里面重寫loadView 方法
- (void)loadView{
self.fView = [[FirstView alloc]init];
self.view = self.fView;//每個viewController都自帶一個view
}
// 視圖已經加載
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];// 設置view背景色
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// 在這個里面處理內存警告問題 (處于安全性考慮)
//重寫處理內存的方法
// 根視圖已經加載過 根視圖未顯示
if ([self isViewLoaded] == YES && self.view.window == nil) {
//將根視圖銷毀
self.view = nil;
}
}
@end
容器視圖控制器
// 創建一個rootViewController 管理其他viewController
@property(nonatomic,retain)RedViewController *redView;
@property (nonatomic,retain)BLueViewController *blueView;
- (void)viewWillAppear:(BOOL)animated{
NSLog(@"將要出現");
}
- (void)viewDidAppear:(BOOL)animated{
NSLog(@"已經出現");
}
- (void)viewWillDisappear:(BOOL)animated{
NSLog(@"將要消失");
}
- (void)viewDidDisappear:(BOOL)animated{
NSLog(@"已經消失");
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"已經加載完成");
self.redView = [[RedViewController alloc]init];
self.blueView = [[BLueViewController alloc]init];
// 添加子視圖控制器
[self addChildViewController:self.redView];
[self addChildViewController:self.blueView];
[self.view addSubview:self.redView.view];
[self.view addSubview:self.blueView.view];
}
```
### 屏幕旋轉
```
viewController.m文件中
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
NSLog(@"將要旋轉");
}
//當旋轉導致 bounds 改變的時候,需要重寫layoutsubview的方法
- (void)layoutSubviews{
if ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationMaskPortrait || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown) {
_label.frame = CGRectMake(100, 100, 100, 200) ;
}else{
_label.frame = CGRectMake(50,50, 300, 100);
}
}
```