一
首先我们把要封装的控件封装到 UIView上;在这里我们先封装label和textfield
1创建UIView的类
LTView.h:
@property(nonatomic,strong)UILabel * label;
@property(nonatomic,strong)UITextField * textField;
LTView.m :将公共的属性设置到.m中
//重写初始化方法
-(instancetype)initWithFrame:(CGRect)frame{
//视图层
if (self = [super initWithFrame:frame]) {
[self setLabel];
[self setTexField];
}
return self;
}
//模块化创建label
//野指针就是没有确定空间的指针
-(void)setLabel{
self.label =[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
self.label.backgroundColor = [UIColor yellowColor];
self.label.textColor = [UIColor purpleColor];
[self addSubview:self.label];
}
//模块化封装输入框
-(void)setTexField{
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(130, 10, 250, 40)];
//圆角矩形
self.textField.borderStyle = UITextBorderStyleRoundedRect;
//删除
self.textField.clearButtonMode = UITextFieldViewModeAlways;
[self addSubview:self.textField];
}
//将非公共的写到根视图的 viewDidLoad中
//方法1
LTView * aView = [[LTView alloc] initWithFrame:CGRectMake(10, 50, 394, 60)];
aView.label.textAlignment = NSTextAlignmentCenter;
aView.label.text = @"账号";
aView.textField.placeholder = @"请输入账号";
aView.backgroundColor = [UIColor redColor];
[self.view addSubview:aView];
LTView * bView = [[LTView alloc] initWithFrame:CGRectMake(10, 130, 394, 60)];
bView.label.text = @"密码";
bView.label.textAlignment = NSTextAlignmentCenter;
bView.textField.placeholder = @"请输入密码";
bView.backgroundColor = [UIColor redColor];
[self.view addSubview:bView];
二.
首先我们先将要封装的控件定义成分类 ,在这里我们封装UIButton
OS X—source ——Object-C File——next —File Type:选择category - class:button-File:(取名为 Create)
UIButton+Create.h:
//在这里我们定义遍历构造器的方法
+(UIButton *)createButtonWithFrame:(CGRect)frame backGround:(UIColor *)color title:(NSString *)title target:(id)target action:(SEL)action;
UIButton+Create.m
(UIButton *)createButtonWithFrame:(CGRect)frame backGround:(UIColor *)color title:(NSString *)title target:(id)target action:(SEL)action{
UIButton * button = [[UIButton alloc] initWithFrame:frame];
button.backgroundColor = color;
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return button;
}
在main.m中的对象定义成属性
@interface ViewController ()
@property(nonatomic,strong)UIButton * tempButton;
@end
-
(void)viewDidLoad {
[super viewDidLoad];
//方法二
//创建按钮
self.tempButton = [UIButton createButtonWithFrame:CGRectMake(50, 200, 100, 40) backGround:[UIColor greenColor] title:@"向日葵" target:self action:@selector(handleAction:)];[self.view addSubview:self.tempButton];
}
//实现点击事件按钮变颜色的方法
-(void)handleAction:(UIButton *)button{
self.tempButton.backgroundColor = [UIColor blackColor];
}