自定义视图
自定义视图就像一个个模板一样,能为我们节省很多代码的书写.自定义视图是多种多样的,今天所写的是最常用的自定义视图之一.页面中往往都是一个Label与之对应着一个TextField,以下便是实现的代码.
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
#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;
}
#import <UIKit/UIKit.h>
@interface LTView : UIView<UITextFieldDelegate>
@property (nonatomic, retain)UILabel *myLabel;
@property (nonatomic, retain)UITextField *myTextField;
@end
#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