LTView 是自寫的繼承於 UIView 的類
這其中創建一個UILabel 和一個 UITextField ;
這樣可以少些一半的代碼.
代碼如下:
LTView.h
#import <UIKit/UIKit.h>
@interface LTView : UIView<UITextFieldDelegate>
// 因爲要在類的外部獲取輸入框的內容,修改Label的標題,所以我們把這兩部分作爲屬性寫在.h這樣在外部可以直接進行修改和設置
@property(nonatomic, retain)UILabel *myLabel;
@property(nonatomic, retain)UITextField *myTextField;
@end
LTView.m
已改爲 MRC !
#import "LTView.h"
@implementation LTView
- (void)dealloc{
[_myLabel release];
[_myTextField release];
[super dealloc];
}
// 重寫默認的初始化方法.
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
// 模塊化
[self createView];
}
return self;
}
- (void)createView{
// 創建兩個子視圖,一個label一個textField
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 25, 70, 30)];
self.myLabel.backgroundColor = [UIColor cyanColor];
self.myLabel.alpha = 0.5;
[self addSubview:self.myLabel];
[_myLabel release];
self.myLabel.textAlignment = NSTextAlignmentCenter;
self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(150, 20, 200, 40)];
self.myTextField.backgroundColor = [UIColor cyanColor];
[self addSubview:self.myTextField];
[_myTextField release];
self.myTextField.layer.cornerRadius = 10;
//設置代理人
self.myTextField.delegate = self;
}
//回收鍵盤方法.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
最後,再創建這樣一個對象
// 創建一個LTView對象
LTView *view = [[LTView alloc] initWithFrame:CGRectMake(0, 100, self.window.frame.size.width, self.window.frame.size.height)];
[self.window addSubview:view]
;
[view release];
view.myLabel.text = @"姓名";
view.myTextField.placeholder = @"請填寫姓名";
如此,效果就同照片一樣了.
這樣創建好LTView之後, 再寫登陸頁面或註冊頁面時就會方便許多.