UI - 组合控件LTView(UILabel + UITextField)

本文详细介绍了如何创建一个自定义的LTView类,用于组合UILabel和UITextField,适用于构建用户友好的登录界面。通过重写初始化方法和属性管理,实现了界面元素的灵活配置。示例代码展示了在AppDelegate中集成LTView实例,用于展示用户名和密码输入框。

很多地方会用到各式各样的控件,如QQ登录界面用户名栏和密码栏都属于LTView(UILabel + UITextField)样式的组合
1>首先新建一个继承于UIView的LTView类

(#LTView.h)

#import <UIKit/UIKit.h>

@interface LTView : UIView
#pragma mark - 2.设置自己内部的控件为属性 但是只给外界提供getter方法,不提供setter 防止外界对其做修改
@property(nonatomic,retain,readonly)UILabel *label;
@property(nonatomic,retain,readonly)UITextField *textField;
@end

(#LTView.m)

#import "LTView.h"

@implementation LTView

#pragma mark -3.重写dealloc方法,注意区分: self,和下划线.
- (void)dealloc
{
    [_label release];
    [_textField release];
    [super dealloc];
}

#pragma mark -1. 重写initWithFrame方法, 在initWithFrame方法的内部定义自己的内部控件
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        CGFloat x = frame.origin.x;
//        CGFloat y = frame.origin.y;
        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;
        _label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width/3, height)];
        [self addSubview:_label];
        /**
         _label 和 self.label不一样, self.label多一次引用计数
         */

        _textField = [[UITextField alloc]initWithFrame:CGRectMake(width/3, 0, width*2/3, height)];

        _textField.borderStyle = UITextBorderStyleRoundedRect;
        [self addSubview:_textField];

    }
    return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

因为是创了空文件工程,所以我是在AppDelegate.m实现的,代码如下

(#AppDelegate.m)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];


    LTView *nameLTView = [[LTView alloc]initWithFrame:CGRectMake(30, 80, 200, 30)];
    nameLTView.label.text = @"用户名";
    nameLTView.textField.placeholder = @"请输入用户名";
    [self.window addSubview:nameLTView];
    [nameLTView release];

    LTView *passwordLTView = [[LTView alloc]initWithFrame:CGRectMake(30, 130, 200, 30)];
    passwordLTView.label.text = @"密码";
    passwordLTView.textField.placeholder = @"请输入密码";
    [self.window addSubview:passwordLTView];
    [passwordLTView release];
  return YES;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值