您的位置:首页 > 产品设计 > UI/UE

iOS开发 UI 自定义视图

2016-01-08 17:29 507 查看
优质代码:高可用,高复用

实现自定义View的步骤:

1 创建一个UIView的子类

2 在初始化方法中添加子视图

3 提供一些接口,给外界操作子视图

自定义视图

1.创建一个viewController和View,还有一个LTview

2.在创建的 LTView.h中

@property(nonatomic,strong)UILabel *label;

@property(nonatomic,strong)UITextField *field;

//声明代理方法

- (void)setDelegate:(id <UITextFieldDelegate>) delegate;

在LTView.m中

- (instancetype)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

[self setupView];

}

return self;

}

- (void)setupView

{

self.label = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 60, CGRectGetHeight(self.frame) - 10)];

self.label.textAlignment = NSTextAlignmentCenter;

[self addSubview:self.label];

CGFloat x = CGRectGetMaxX(self.label.frame) + 20;

CGFloat y = CGRectGetMinY(self.label.frame);

CGFloat width = CGRectGetWidth(self.frame) - 10 - 20 - CGRectGetWidth(self.label.frame);

CGFloat height = CGRectGetHeight(self.label.frame);

self.field = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];

self.field.borderStyle = UITextBorderStyleRoundedRect;

[self addSubview:self.field];

}

//实现代理方法

- (void)setDelegate:(id <UITextFieldDelegate>) delegate

{

self.field.delegate = delegate;

}

3.在创建的View中,引入LTView头文件

#import "RootView.h"

#import "LTView.h"

@implementation RootView

- (instancetype)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

[self setupView];

}

return self;

}

- (void)setupView

{

self.backgroundColor = [UIColor cyanColor];

LTView *view1 = [[LTView alloc]initWithFrame:CGRectMake(20, 30, CGRectGetWidth(self.frame) - 40, 40)];

view1.label.text = @"用户名";

[self addSubview:view1];

LTView *pwd = [[LTView alloc]initWithFrame:CGRectMake(20, 90, CGRectGetWidth(view1.frame), 40)];

pwd.label.text = @"密码";

[self addSubview:pwd];

LTView *qux = [[LTView alloc]initWithFrame:CGRectMake(20, 150, CGRectGetWidth(view1.frame), 40)];

qux.label.text = @"取向";

[self addSubview:qux];

[view1 setDelegate:self];

[pwd setDelegate:self];

[qux setDelegate:self];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

[textField resignFirstResponder];

return YES;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: