一、自定义视图(label-textField组合视图)
自定义视图:系统标准UI之外,自己组合而出的新的视图。
示例:创建一个登录界面
登录界面的特点:每一行左边是label,右边是textField。
把label和textField封装到LTView中。
LTView *lt = [[LTView alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
lt.backgroundColor = [UIColor redColor];
//分别给lt上的控件赋颜色
lt.label.backgroundColor = [UIColor yellowColor];
lt.label.text = @"用户名";
lt.tf.backgroundColor = [UIColor cyanColor];
lt.tf.placeholder = @"请输入用户名";
二、视图控制器
UIViewController:视图控制器,用来管理视图。是MVC架构中重要的一环。每个视图控制器都会自带一个根视图,为了管理受视图控制器管理的所有视图。
视图控制器所负责的事情:
1. 控制视图大小变换、布局视图、响应事件。
2. 检测以及处理内存警告。
3. 检测以及处理屏幕旋转。
4. 检测视图的切换。
5. 实现模块独立,提高复用性。
三、MVC
MVC:一个框架级的设计模式。M是Model,主要用于建立数据模型。V是View,主要用于展示数据。C是控制器,主要用于控制M和V的通信。
四、屏幕旋转
检测屏幕旋转:
//视图控制器本身能检测到屏幕的旋转,如果要处理屏幕旋转,需要重写几个方法:
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
//设置设备支持旋转的方向,如果不添加,视图控制器将无法检测屏幕的旋转
return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//在该方法中,我们可以暂停音频,视频, 游戏播放,关闭视图交互等操作.
NSLog(@"屏幕即将旋转");
}
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//添加自定义动画等
NSLog(@"做动画");
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
//在该方法中,重新打开暂停的音频,视频,游戏,打开视图的用户交互.
NSLog(@"视图已经旋转完成");
}
视图的处理:
注意视图控制器会自动调整view的大小以适应屏幕旋转,bounds被修改,触发view的layoutSubviews方法。
view重写layoutSubviews方法,根据设备方向,重新布局。
[UIApplication sharedApplication].statusBarOrientation提供设备当前方向。
五、内存警告
内存警告来源:手机内存80M,程序运行过程中内存接近80M时程序会为每一个视图控制器发送内存警告消息。
如何处理:
控制器能检测内存警告,以便我们避免内存不够引起的crash。
在定义的Controller子类中重写didReceiveMemoryWarning方法。
释放暂时不使用的资源(self.view及view的子视图例如数据对象、图像)。