UI_LTView自定义视图

来源:互联网 发布:帝国cms养生采集规则 编辑:程序博客网 时间:2024/05/21 23:32


自定义视图

自定义视图就像一个个模板一样,能为我们节省很多代码的书写.自定义视图是多种多样的,今天所写的是最常用的自定义视图之一.页面中往往都是一个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];

    [superdealloc];

}



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

    self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColorwhiteColor];

    [self.windowmakeKeyAndVisible];

    

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

    

    view.myLabel.text =@"King";

    view.myTextField.placeholder =@"Queen";

    [self.windowaddSubview:view];

    

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

    

    view1.myLabel.text =@"King";

    view1.myTextField.placeholder =@"Queen";

    [self.windowaddSubview:view1];

    

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

    

    [viewrelease];

    [view1release];

    [_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];

    [superdealloc];

}


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

- (instancetype)initWithFrame:(CGRect)frame

{

   self = [superinitWithFrame:frame];

   if (self) {

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

        [selfcreate];

    }

    return self;

}


- (void)create

{

    //创建一个label

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

    [selfaddSubview:self.myLabel];

   

    

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

    [selfaddSubview: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.myTextFieldresignFirstResponder];

    return YES;

}

@end



1 0