標籤:
自訂視圖
例如,登陸頁面中,左邊label,右邊textField。自訂
@interface LTView : UIView@property (nonatomic,retain) UILabel *label;@property (nonatomic,retain) UITextField *textField;- (instancetype)initWithFrame:(CGRect)frame text:(NSString *)text placeHolder:(NSString *)placeHolder;@end
@implementation LTView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
//定義寬和高
CGFloat w = frame.size.width;
CGFloat h = frame.size.height;
self.label = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, w/3 - 15, h - 10)];
[self addSubview:self.label];
self.textField = [[UITextField alloc]initWithFrame:CGRectMake(w/3 - 5, 5, 3*w / 3, h - 10)];
self.textField.layer.cornerRadius = 8;
self.textField.layer.borderWidth = 1;
[self addSubview:self.textField];
[self.label release];
[self.textField release];
}return self;
}
- (void)dealloc{
[self.label release];
[self.textField release];
[super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame text:(NSString *)text placeHolder:(NSString *)placeHolder{
self = [self initWithFrame:frame];
if (self) {
self.label.text = text;
self.textField.placeholder = placeHolder;
}
return self;
}
視圖控制器
概述UIViewController:視圖控制器
控制視圖顯示,回應時間
分擔AppDelegate的工作
實現模組獨立,提高複用性
功能
控制視圖大小變化,布局視圖,響應事件
檢測以及處理記憶體警告
檢測以及處理旋轉螢幕
檢測視圖的切換
MVC概述
UIViewController是MVC設計模式的核心
MVC是一個架構級的設計模式
M是Model,主要用於建立資料模型
V是View,View主要功能是展示資料
C是控制器,主要是控制M和V的通訊
UIViewController內建一個空的View,與需求不符合,
視圖控制器只負責控制視圖顯示,響應事件
所以使用自訂視圖類:
1.自訂視圖繼承UIView,在初始化方法中添加子視圖控制項
2.重寫controller的loadView方法,建立自訂試圖對象,並指定為controller的View
3.將子視圖控制項對象設定為自訂視圖類的屬性,在viewDidLoad方法中進行設定
@implementation ViewController-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { NSLog(@"1 "); }return self;}- (void)loadView{ [super loadView]; //重寫 UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds]; view.backgroundColor = [UIColor brownColor]; self.view = view; NSLog(@"2");}-(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:YES]; NSLog(@"3");}- (void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:YES]; NSLog(@"4");}
//視圖控制器功能一、//1.檢測並回應時間//2.視圖的整體布局//3.檢測旋轉螢幕//4.檢測並處理記憶體警告//1.螢幕能否旋轉(預設旋轉)- (BOOL)shouldAutorotate{ return YES;}//螢幕能旋轉的方向- (NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskAllButUpsideDown;}
//記憶體警告- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; //如果視圖被載入,而且視圖沒有顯示,將其release if ([self isViewLoaded] == YES && self.view.window == nil) { self.view = nil; } // Dispose of any resources that can be recreated.}
iOS基礎-自訂視圖、視圖控制器