⾃定义视图:系统标准UI之外,⾃自⼰组合而出的新的视图。
根据需求的不同,自定义视图继承的类也有所不同。一般自定义的视图会继承于UIView。以下是自定义视图的要点:
1、创建⼀个UIView子类
2、在类的初始化方法中添加⼦视图
3、类的.h文件提供一些接口(⽅法),便于外界操作⼦视图。
假设使用LTView类代表label-textfield视图, 创建⼀个LTView类继承于UIView, 将LTView作为一个容器, 在LTView的初始化方法中创建并添
加label和textField。此时的LTView就变成了一个具有label和textField的视图了。
⾃定义LTView使用了一种设计模式:复合设计模式。复合设计模式:A类中,使用B类(或者更多类)作为自己的成员(实例变量)。
代码实现如下:
LTView.h
@interface LTView : UIView
@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UITextField *textField;
@end
LTView.m
@implementation WJQ_LTView
- (void)dealloc {
[_label release];
[_textField release];
[super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, 40)];
self.label.font = [UIFont systemFontOfSize:16];
[self addSubview:self.label];
[self.label release];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(80, 0, 220, 40)];
self.textField.font = [UIFont systemFontOfSize:16];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.clearButtonMode = UITextFieldViewModeAlways;
[self addSubview:self.textField];
[self.textField release];
}
return self;
}