您的位置:首页 > 产品设计 > UI/UE

iOS编程-------自定义视图CustomView 封装视图LTView 视图控制器UIViewController

2015-10-04 22:22 549 查看
//
//  AppDelegate.h
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

//
//  AppDelegate.m
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "AppDelegate.h"
#import "LTView.h" //导入自定义控件头文件
#import "LoginView.h"
#import "RootViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate
#pragma mark 重写dealloc
- (void)dealloc{
[_window release];
[super dealloc];
}
//程序执行成功后,执行的加载方法,已经加载完成,创建window等操作
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"%s %d", __FUNCTION__, __LINE__);
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

//一. 自定义视图
//在工作中,我们通常把重复使用的控件,封装为一个自定义控件.比如,把label textField 封装为 LTView.

//创建自定义视图
//    LTView *userNameLTView = [LTView lTViewWithFrame:(CGRectMake(50, 50, 300, 40)) labelWidth:80 text:@"用户名" placeHolder:@"请输入用户名"];
//    [self.window addSubview:userNameLTView];

//创建loginView
//    _loginView = [[LoginView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
//    [self.window addSubview:_loginView];

//***********************************

// MVC 框架
// M Model (模型层)主要负责数据库的映射,可以认为是本地的数据容器
// V View (视图层)主要负责UI的渲染和显示,控件的添加都放在View层
// C Controller (控制层)主要负责业务逻辑的实现和控制View层和Model层的解析数据等。

// controller 分担了appdelegate压力,使功能模块化。
//MVC 框架可以使各个层次各司其职,便于之后的维护和管理

//创建一个根试图控制器
RootViewController *rootVC = [[RootViewController alloc] init];
//把rootVC设置为window的根控制器
self.window.rootViewController = rootVC;
[rootVC release];
//上面的代码相当于做了以下实现
//    [self.window addSubview:rootVC]
//把rootVC的试图添加到window上面用于显示

return YES;
}

//程序将要注销活跃状态
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"%s %d", __FUNCTION__, __LINE__);
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
//程序已经进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"%s %d", __FUNCTION__, __LINE__);
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
//程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {

NSLog(@"%s %d", __FUNCTION__, __LINE__);

// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
//程序已经进入活跃状态
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"%s %d", __FUNCTION__, __LINE__);
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
//程序将要结束
- (void)applicationWillTerminate:(UIApplication *)application {
NSLog(@"%s %d", __FUNCTION__, __LINE__);

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

///////////////////////////////////////////////////////////////////////////////

//
//  RootViewController.h
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController /*<UITextFieldDelegate> */

@end

//
//  RootViewController.m
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "RootViewController.h"
#import "LoginView.h" //导入登录视图头文件
#import "LTView.h"//导入LTView头文件
#import "SecondViewController.h"
@interface RootViewController ()<UITextFieldDelegate> //遵守协议
@property (nonatomic, retain) LoginView *loginView;

@end

@implementation RootViewController
- (void)dealloc{
[_loginView release];
[super dealloc];
}

//*****************************

//让controller实现键盘回收方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
//    textField 是正在响应的输入框,如果用户正在操作的是用户名输入框,传递过来的就是用户名textField,如果正在操作的是密码输入框,传递过来的就是密码textField
//    [textField resignFirstResponder];
//如果是用户名输入框,则跳到下一行
if ([textField isEqual:_loginView.userNameLTView.textField]) {
[textField resignFirstResponder];
//让密码输入框成为第一响应者
[_loginView.pwdLTView.textField becomeFirstResponder];
}else{
//否则,说明当前textField是密码输入框
[textField resignFirstResponder];

}
return YES;
}

//******************

// ViewController 的loadView 方法,默认给controller加载了一个空视图,该视图无色,等屏大小
- (void)loadView{
// loadView 方法,就只有一个作用,加载一个空视图
// 如果controller自带的视图,满足不了我们的需求,我们可以重写loadView,指定controller的视图为自定义视图
// self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen]bounds]] autorelease];
// self.view.backgroundColor = [UIColor yellowColor];

//****************
// 加载登录视图头文件
//    _loginView = [[[LoginView alloc] initWithFrame:[[UIScreen mainScreen]bounds]] autorelease];
//    self.view = _loginView;

/*    self.view = [[[LoginView alloc] initWithFrame:[[UIScreen mainScreen]bounds]] autorelease];
*/

//**************

//self.view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
//    self.view.backgroundColor = [UIColor redColor];

}

//******************

// viedDidLoad方法紧跟着loadView方法执行的,先执行的是loadView方法,后执行的是viewDidLoad方法.
- (void)viewDidLoad {
[super viewDidLoad];

// 添加子控制器
SecondViewController *secondVC = [[SecondViewController alloc] init];
[self addChildViewController:secondVC];

[self.view addSubview:secondVC.view];

// 一个视图仅能作为 一个控制器的 view。

//    self.view = secondVC.view;

//******************

//给密码框设置为密文输入
_loginView.pwdLTView.textField.secureTextEntry = YES;

//练习三
//让controller实现键盘回收方法
_loginView.userNameLTView.textField.delegate = self;//此时self是controller
_loginView.pwdLTView.textField.delegate = self;

//给登录按钮添加点击事件
//此时self是rootController,就是我们创建的rootVC对象.
[_loginView.loginButton addTarget:self action:@selector(loginAction) forControlEvents:(UIControlEventTouchUpInside)];

//    self.view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
//    self.view.backgroundColor = [UIColor redColor];

// Do any additional setup after loading the view.
}

//*****************

//controller实现loginButton点击事件
- (void)loginAction{
NSLog(@"登录");
}

//****************

//四. controller 可以检测到屏幕旋转.但是,如果要处理屏幕旋转必须要实现几个方法.
//1.是否能够旋转
- (BOOL)shouldAutorotate{
return YES;//系统默认实现的方法,返回值默认为YES,可以旋转.如果设置为NO,不可以旋转
}
//2.支持屏幕旋转的方向
- (NSUInteger)supportedInterfaceOrientations{
//返回值为一个枚举值
return UIInterfaceOrientationMaskAll;//所有方向
}

// 3. 屏幕旋转时触发的方法 iOS8 已经弃用
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"将要旋转到目标方向");
}

// 4. 已经旋转到目标方向 已经弃用
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
NSLog(@"已经旋转到目标方向");
}

//ios8.0 之后的新方法
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
if (size.width > size.height) {
NSLog(@"横屏");
}else{
NSLog(@"竖屏");
}
}

//***********************

//释放视图 6.0 之前会在里面做一些释放内存资源的操作
- (void)viewWilllUnload{
NSLog(@"释放视图");
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
NSLog(@"接收到内存警告");
//内存不够用的时候,会接收到内存警告,此时我们把已经加载过的视图,正在占用内存资源的且不是正在显示的给释放掉.
if ([self isViewLoaded] && self.view.window == nil) {
//如果视图控制器已经加载,但是没有使用,把视图给释放掉(根视图已经加载过,根视图未显示)
self.view = nil;//将根视图销毁
}

// Dispose of any resources that can be recreated.
}

@end

/////////////////////////////////////////////////////////////////////////////

//
//  SecondViewController.h
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

@end

//
//  SecondViewController.m
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

//*****************

- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
button.frame = CGRectMake(100, 100, 100, 100);

[button setTitle:@"移除" forState:(UIControlStateNormal)];

[button addTarget:self action:@selector(removeAction) forControlEvents:(UIControlEventTouchUpInside)];

[self.view addSubview:button];

}

- (void)viewWillAppear:(BOOL)animated{
NSLog(@"视图将要显示");
}
- (void)viewDidAppear:(BOOL)animated{
NSLog(@"视图已经显示");
}
- (void)viewWillDisappear:(BOOL)animated{
NSLog(@"视图将要消失");
}
- (void)viewDidDisappear:(BOOL)animated{
NSLog(@"视图已经消失");
}

//***************

- (void)removeAction{
//从父控制器中移除,本控制器.
[self removeFromParentViewController];
[self.view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

/////////////////////////////////////////////////////////////////////////////

//
//  LoginView.h
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>
@class LTView; //避免造成循环引用和节省加载, @class 说明LTView 是一个类
@interface LoginView : UIView

//此为登录视图,里面有5个控件分别为 userNameLTView pwdLTView 3个Button

@property (nonatomic, retain, readonly) LTView *userNameLTView;//用户名
@property (nonatomic, retain, readonly) LTView *pwdLTView;//密码
@property (nonatomic, retain, readonly) UIButton *loginButton;//登录按钮
@property (nonatomic, retain, readonly) UIButton *registButton;//注册按钮
@property (nonatomic, retain, readonly) UIButton *findPWDButton;//找回密码按钮

@end

//
//  LoginView.m
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "LoginView.h"
#import "LTView.h"

@implementation LoginView
#pragma mark 重写dealloc
- (void)dealloc{
[_userNameLTView release];
[_pwdLTView release];
[super dealloc];
}

//重写loginView 的初始化方法
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
//创建内部控件
//userNameLTView
_userNameLTView = [[LTView alloc] initWithFrame:(CGRectMake(50, 50, 300, 40)) labelWidth:80 text:@"用户名" placeHolder:@"请输入用户名"];

[self addSubview:_userNameLTView];
//pwdNameLTView
_pwdLTView = [[LTView alloc] initWithFrame:(CGRectMake(50, 100, 300, 40)) labelWidth:80 text:@"密码" placeHolder:@"请输入密码"];
[self addSubview:_pwdLTView];
//loginButton
_loginButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
[_loginButton setTitle:@"登录" forState:(UIControlStateNormal)];
_loginButton.frame = CGRectMake(50, 200, 50, 44);
[self addSubview:_loginButton];
//resigt
_registButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
[_registButton setTitle:@"注册" forState:(UIControlStateNormal)];
_registButton.frame = CGRectMake(150, 200, 80, 44);
[self addSubview:_registButton];
//pwd
_findPWDButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
[_findPWDButton setTitle:@"找回" forState:(UIControlStateNormal)];
_findPWDButton.frame = CGRectMake(230, 200, 120, 44);
[self addSubview:_findPWDButton];

}
return self;
}

//**************

//controller 在屏幕旋转的时候,改变的是view自身的大小,并不会改变controller.view里面的子视图的大小
//改变子视图的大小需要在view里面进行操作
//重写layoutSubViews布局子视图方法
- (void)layoutSubviews{
//1.获取当前屏幕的方向
//获取应用程序[UIApplication sharedApplication]
//获取屏幕方向statusBarOrientation
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIInterfaceOrientationLandscapeRight || orientation == UIInterfaceOrientationLandscapeLeft) {
//如果是横屏,改变内部子视图的位置
CGRect rec1 = _userNameLTView.frame;
rec1.origin.x = 150;
_userNameLTView.frame = rec1;
}else{
CGRect rec2 = _userNameLTView.frame;
rec2.origin.x = 50;
_userNameLTView.frame = rec2;
}
}

//*********************

@end

//////////////////////////////////////////////////////////////////////////////

//
//  LTView.h
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>
/*
LTView 中有两个控件,一个是label在左边,另一个是textField在右边.
label  textField
*/
@interface LTView : UIView

//label 控件
@property(nonatomic, retain, readonly)UILabel *label;
//textField 控件
@property(nonatomic, retain, readonly)UITextField *textField;
//设置为readonly 让外界不能改变我们内部的控件

//如果我们想要LTView,创建出来就自带一些属性,就需要重写它的构造方法,也就是自定义方法init
//重写构造方法,自定义初始化方法
//frame确定了LTView的x,y,width,height
//labelWidth为label的宽度
//text为label的标题
//placeholder为占位符
//这四个参数是我们提供给外界的接口
- (instancetype)initWithFrame:(CGRect)frame labelWidth:(CGFloat)labelWidth text:(NSString *)text placeHolder:(NSString *)placeholder;

//创建一个便利构造器
+ (LTView *)lTViewWithFrame:(CGRect)frame labelWidth:(CGFloat)labelWidth text:(NSString *)text placeHolder:(NSString *)placeholder;

//
//  LTView.m
//  UI03-custonView\LTView\Controller
//
//  Created by t on 15/9/2.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "LTView.h"
//#define kHorizonSpacing 10 //水平间距

@implementation LTView
#pragma mark 重写dealloc
- (void)dealloc{
[_label release];
[_textField release];
[super dealloc];
}

//自定义初始化方法
- (instancetype)initWithFrame:(CGRect)frame labelWidth:(CGFloat)labelWidth text:(NSString *)text placeHolder:(NSString *)placeholder{
//调用父类的initWithFrame初始化方法
self = [super initWithFrame:frame];
if (self) {
//对LTView进行初始化,加载textField以及label
CGFloat totalWidth = self.frame.size.width;//LTView的宽度
CGFloat totalHeight = self.frame.size.height;//LTView的高度
//创建label子视图
_label = [[UILabel alloc] initWithFrame:(CGRectMake(0, 0, labelWidth, totalHeight))];
_label.text = text;
[self addSubview:_label];//把_label添加到LTView上

//创建textField
_textField = [[UITextField alloc] initWithFrame:(CGRectMake(labelWidth   + 10, 0, totalWidth - labelWidth - 10, totalHeight))];
_textField.placeholder = placeholder;//外界给定的placeholder
_textField.borderStyle = UITextBorderStyleRoundedRect;
[self addSubview:_textField];//添加到LTView上
}
return self;
}

//便利构造器
+ (LTView *)lTViewWithFrame:(CGRect)frame labelWidth:(CGFloat)labelWidth text:(NSString *)text placeHolder:(NSString *)placeholder{
return [[[LTView alloc] initWithFrame:frame labelWidth:labelWidth text:text placeHolder:placeholder] autorelease];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: