// AppDelegate.m
#import "AppDelegate.h"
#import "LTView.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
-(void)dealloc{
[_window release];
[super dealloc];
}
// 创建自定义视图的步骤
//1,创建基于UIView的视图LTView
//2,在LTView的.h中声明子视图为属性
//3,释放子视图的两个属性
//4,重写初始化方法
//5,懒加载创建 self.titleLable和 self.inputTextField
//6,在AppDelegate.m中调用自定义视图
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
//6,在AppDelegate.m中调用自定义视图
//单行布局,用自定义视图(LTView)
//多行布局,用自定义视图(LTView),for循环
NSArray*titles=@[@[@"用户名",@"请输入用户名"],@[@"密码",@"请输入密码"],@[@"确认密码",@"再次输入密码"],@[@"邮箱",@"请输入邮箱"]];
for (int i=0; icount; i++) {
NSArray*title=titles[i];
LTView*aView=[[LTView alloc]initWithFrame:CGRectMake(0, 100+50*i, 0, 0)];
aView.backgroundColor=[UIColor colorWithRed:arc4random()%6/255.0 green:arc4random()%6/255.0 blue:arc4random()%6/255.0 alpha:0.8];
aView.titleLable.text=title[0];
aView.inputTextField.placeholder=title[1];
[self.window addSubview:aView];
}
return YES;
}
#import
@interface LTView : UIView
// 设计自定义视图时声明子视图为属性,是为了方便将来实例化对象后,依然可以通过属性访问到其子视图,为子视图的相关属性赋值,例如titleLable的text属性
@property(nonatomic,retain)UILabel*titleLabel;
@property(nonatomic,retain)UITextField*inputTextField;
@end
#import "LTView.h"
@interface LTView()
{
CGRect _frame;
}
@end
@implementation LTView
//3,释放子视图的两个属性
-(void)dealloc{
[_titleLable release];
[_inputTextField release];
[super dealloc];
}
//4,重写初始化方法
-(instancetype)initWithFrame:(CGRect)frame{
frame=CGRectMake(0, frame.origin.y, CGRectGetWidth([[UIScreen mainScreen]bounds]), 40) ;
self=[super initWithFrame:frame];
if (self) {
//懒加载里的内容可以放此处,代替懒加载
}
return self;
}
//5,懒加载
-(UILabel *)titleLable{
if (!_titleLable) {//不存在
CGFloat width=(CGRectGetWidth(self.frame)-50)/7;
//创建Lable
self.titleLable=[[[UILabel alloc]initWithFrame:CGRectMake(30, 5, width*2, 30)]autorelease];
[self addSubview:self.titleLable];
}
return _titleLable;
}
-(UITextField *)inputTextField{
if (!_inputTextField) {
CGFloat width=(CGRectGetWidth(self.frame)-50)/7;
self.inputTextField=[[[UITextField alloc]initWithFrame:CGRectMake(self.titleLable.frame.origin.x+CGRectGetWidth(self.titleLable.frame)+5, 5, width*5, 30)]autorelease];
self.inputTextField.borderStyle=UITextBorderStyleRoundedRect;
self.inputTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
[self addSubview:self.inputTextField];
}
return _inputTextField;
}
@end