LTView:全称label , textField , view
创建一个LTView类继承于UIView
LTView.h
#import <UIKit/UIKit.h>
1.在LTView.h文件中签订协议UITextFieldDelegate.
@interface LTView : UIView<UITextFieldDelegate>
2.因为LTView里的label和textField需要在外面设置一些内容,所以需要在.h文件里把他们设置成属性.
@property(nonatomic, retain)UILabel *myLabel;
@property(nonatomic, retain)UITextField *myTextField;
@end
LTView.m
#import "LTView.h"
@implementation LTView
3.重写initWithFrame方法.
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self creatView];
}
return self;
}
- (void)creatView {
4.创建label
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 150, 50)];
self.myLabel.layer.borderWidth = 1;
self.myLabel.layer.cornerRadius = 10;
[self addSubview:self.myLabel];
[_myLabel release];
5.创建textField
self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 20, 150, 50)];
self.myTextField.layer.borderWidth = 1;
self.myTextField.layer.cornerRadius = 10;
[self addSubview:self.myTextField];
[_myTextField release];
self.myTextField.clearButtonMode = UITextFieldViewModeAlways;
self.myTextField.delegate = self;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self.myTextField resignFirstResponder];
return YES;
}
- (void)dealloc
{
[_myLabel release];
[_myTextField release];
[super dealloc];
}
AppDelegate.m
#import "AppDelegate.h”
#import “LTView.h” // 引入LTView的头文件.
@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];
[_window release];
// 用LTView来创建视图.
LTView *view = [[LTView alloc] initWithFrame:CGRectMake(0, 50, 375, 100)];
view.backgroundColor = [UIColor greenColor];
[self.window addSubview:view];
[view release];
return YES;
}
注意:如果label或者textField的大小超出了LTView的范围,那么超出的范围没有功能性,只有显示性.