UI_LTView自定义视图


自定义视图

自定义视图就像一个个模板一样,能为我们节省很多代码的书写.自定义视图是多种多样的,今天所写的是最常用的自定义视图之一.页面中往往都是一个Label与之对应着一个TextField,以下便是实现的代码.



AppDelegate.h

#import <UIKit/UIKit.h>


@interface AppDelegate : UIResponder <UIApplicationDelegate>


@property (strong, nonatomic) UIWindow *window;


@end


AppDelegate.m

#import "AppDelegate.h"

#import "LTView.h"

@interface AppDelegate ()


@end


@implementation AppDelegate

-(void)dealloc

{

    [_window release];

    [super dealloc];

}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    

    LTView *view = [[LTView alloc] initWithFrame:CGRectMake(20, 80, self.window.frame.size.width - 20, 70)];

    

    view.myLabel.text = @"King";

    view.myTextField.placeholder = @"Queen";

    [self.window addSubview:view];

    

    LTView *view1 = [[LTView alloc] initWithFrame:CGRectMake(20, 200, self.window.frame.size.width - 20, 70)];

    

    view1.myLabel.text = @"King";

    view1.myTextField.placeholder = @"Queen";

    [self.window addSubview:view1];

    

    //    [[LTView alloc] init] 该方法没有重写

    

    [view release];

    [view1 release];

    [_window release];

    return YES;

}


LTView.h

#import <UIKit/UIKit.h>


@interface LTView : UIView<UITextFieldDelegate>


@property (nonatomic, retain)UILabel *myLabel;

@property (nonatomic, retain)UITextField *myTextField;


@end


LTView.m

#import "LTView.h"


@implementation LTView

- (void)dealloc

{

    [_myTextField release];

    [_myLabel release];

    [super dealloc];

}


// 1. 重写父类的初始化方法

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        //两个视图,随着TLView的初始化,也完成创建

        [self create];

    }

    return self;

}


- (void)create

{

    //创建一个label

    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 20, 100, 40)];

    [self addSubview:self.myLabel];

   

    

    self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 20, 200, 40)];

    [self addSubview:self.myTextField];

  

    self.myTextField.layer.borderWidth = 1;

    self.myTextField.layer.cornerRadius = 6;

    self.myTextField.clearButtonMode = UITextFieldViewModeAlways;

    [_myLabel release];

    [_myTextField release];

    //设置代理人

    self.myTextField.delegate = self;

}


- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [self.myTextField resignFirstResponder];

    return YES;

}

@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值