声明
a.h 文件
+ (UILabel *) createLabelWithText: (NSString *) text;
+ (UITextField *) createTextFieldWithPlaceHolder: (NSString *) placeHolder hasPassword: (BOOL) hasPwd;
+ (UIButton *) createButtonWithTitle: (NSString *) title WithTarget: (id ) target withAction: (SEL ) action ;
+ (void)addViews: (NSArray<UIView *> *) views OnViewController: (UIViewController *) viewController;
实现
.m 文件
+ (UILabel *)createLabelWithText:(NSString *)text {
UILabel * label = [[UILabel alloc ] init ];
if (text) {
label.text = text;
}
return label;
}
+ (UITextField *)createTextFieldWithPlaceHolder:(NSString *)placeHolder hasPassword:(BOOL)hasPwd {
UITextField * textField = [[UITextField alloc ] init ];
if (placeHolder ) {
textField.placeholder = placeHolder;
}
textField.borderStyle = UITextBorderStyleRoundedRect;
if (hasPwd ) {
textField.secureTextEntry = YES;
}
return textField ;
}
+ (UIButton *)createButtonWithTitle:(NSString *)title WithTarget:(id)target withAction:(SEL)action {
UIButton * button = [[UIButton alloc ] init ];
if (title) {
[button setTitle: title forState:UIControlStateNormal ];
}
if ( target && action ) {
[button addTarget: target action:action forControlEvents:UIControlEventTouchUpInside ];
}
return button ;
}
+ (void)addViews:(NSArray<UIView *> *)views OnViewController:(UIViewController *)viewController {
for (UIView * view in views ) {
[viewController.view addSubview: view ];
}
}
应用
LoginViewController
@implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor ];
UILabel * nameLabel = [Util createLabelWithText:@"用户名: " ];
nameLabel.frame = CGRectMake(40, 100, 80, 40);
[Util addViews:@[nameLabel] OnViewController:self];