当前位置: 首页 > 工具软件 > LTView > 使用案例 >

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

司徒焕
2023-12-01

很多地方会用到各式各样的控件,如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;
}
 类似资料: