2. 创建自定义视图类
3. 将自定义视图的View替换自带的View
3.1 引入
3.2 写属性
3.3 dealloc
3.4 重写loadView
4. 设置好页面
4.1 声明属性
4.2 dealloc方法
4.3 创建视图元素,然后添加到页面上
5. 给button绑定事件(Controller里)
5.1 绑定事件写在 viewDidLoad
5.2 在viewDidLoad方法下面去实现事件
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// 设置window
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
[self.window release];
// 设置根视图控制器
LoginViewController *loginVC = [[LoginViewController new] autorelease];
self.window.rootViewController = loginVC;
LoginViewController.m
@interface LoginViewController () <UITextFieldDelegate>
// 在延展里声明私有的属性
// 声明替换掉自带View的自定义View
@property (nonatomic, retain) LoginView *loginView;
@end
@implementation LoginViewController
#pragma mark - 当我们需要设置自定义视图时,需要重写loadView
- (void)loadView
{
// 1. 创建自定义View
self.loginView = [[[LoginView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
// 2. 替换自带的VIew
self.view = _loginView;
}
#pragma mark - 绑定事件、设置代理、处理逻辑、处理数据
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 给button绑定那个事件
[_loginView.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
_loginView.textField.delegate = self;
}
#pragma mark - Button绑定的事件
- (void)buttonAction:(UIButton *)sender
{
NSLog(@"Button被点击了");
}
#pragma mark - 实现协议的方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)dealloc
{
[_loginView release];
[super dealloc];
}
@end
LoginView.h
@interface LoginView : UIView
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UITextField *textField;
@end
LoginView.m
@implementation LoginView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor blueColor];
[self addSubview];
}
return self;
}
#pragma mark 添加所有的视图元素
- (void)addSubview
{
// 1. 创建button并添加
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
[_button setTitle:@"我是一个Button" forState:UIControlStateNormal];
_button.frame = CGRectMake(100, 100, 200, 30);
_button.backgroundColor = [UIColor cyanColor];
[self addSubview:_button];
// 2. 创建textField并添加
self.textField = [[[UITextField alloc] initWithFrame:CGRectMake(100, 200, 200, 30)] autorelease];
_textField.borderStyle = UITextBorderStyleRoundedRect;
[self addSubview:_textField];
}
- (void)dealloc
{
[_button release];
[_textField release];
[super dealloc];
}
@end