iOS_UI_5_user-defined(自定义)View

来源:互联网 发布:淘宝店铺详情页设计 编辑:程序博客网 时间:2024/06/05 11:44

一. 自定义视图定义
高质量代码的特点: 可复用, 可移植, 精炼.

自定义视图: 系统标准UI之外, 自己组合而出的新的视图.自定义视图,不仅能够实现高质量的代码, 实际开发中, 我们还需要自定义视图. 积累自己的代码库. 方便开发. 自己封装的视图,能像系统UI控件一样, 用于别的项目中, 能大大的降低开发成本, 提高开发效率.

二 . 自定义视图 Instance

// 1. 创建一个UIVIew子类// 2. 在类的初始化方法中添加子视图// 3. 类的.h 文件提供一些接口(方法), 便于外界操作子视图.// 如:// 创建一个登录页面的自定义视图//1. 创建一个UIView子类LoginView 在.h中定义属性//  LoginView.h#import <UIKit/UIKit.h>@interface LoginView : UIView@property (nonatomic, retain) UILabel *nameLable;@property (nonatomic, retain) UITextField *nameTextField;@property (nonatomic, retain) UILabel *passWordLable;@property (nonatomic, retain) UITextField *passWordTextField;@end// 2. .m 文件中初始化view//  LoginView.m#import "LoginView.h"@implementation LoginView- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        [self p_setupView];    }    return self;}- (void) p_setupView{    // nameLable    _nameLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];    [self addSubview:_nameLable];    // nameTextField   _nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_nameLable.frame) + 10, CGRectGetMinY(_nameLable.frame), 150, 40)];    _nameTextField.borderStyle = UITextBorderStyleNone;    [self addSubview:_nameTextField];    // PassWordLable    _passWordLable = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(_nameLable.frame), CGRectGetMaxY(_nameLable.frame), 100, 40)];    [self addSubview:_passWordLable];    // PassWordTextField    _passWordTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_passWordLable.frame) + 10, CGRectGetMinY(_passWordLable.frame), 150, 40)];    _passWordTextField.borderStyle = UITextBorderStyleNone;    [self addSubview:_passWordTextField];    }@end// 之后就可以使用了,自定义的视图了//  AppDelegate.m#import "AppDelegate.h"#import "LoginView.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];// 创建一个自定义的LoginView, 并设置它的属性    LoginView *myLoginView = [[LoginView alloc] initWithFrame:CGRectMake(20, 50, self.window.frame.size.width - 40, 100)];    myLoginView.backgroundColor = [UIColor brownColor];    // name    myLoginView.nameLable.text = @"用户名:";    myLoginView.nameLable.textAlignment = NSTextAlignmentCenter;    myLoginView.nameTextField.placeholder = @"输入用户名";    // passWord    myLoginView.passWordLable.text = @"密码:";    myLoginView.passWordLable.textAlignment = NSTextAlignmentCenter;    myLoginView.passWordTextField.secureTextEntry = YES;    myLoginView.passWordTextField.placeholder = @"输入密码";    // 添加到window     [self.window addSubview:myLoginView];    return YES;}
0 0