iOS-视图控制器

视图控制器指定自定义View

自定义视图类继承UIView。在初始化方法中添加子视图控件。
重写controller的loadView方法。创建自定义视图对象,并指定为controller的view。(注:loadView方法在控制器的view为nil的时候被调用,用于以编程的方式创建view的时候用到。loadView是使用代码生成视图的时候,当视图第一次载入的时候调用的方法,用于使用(写)代码来实现控件。)
将子视图控件对象设置为自定义视图类的属性,在viewDidLoad方法中进行设置:添加action、设置delegate等等。
在controller中添加按钮点击事件实现和代理方法的实现。

一个下案例,点击button跳转到下一界面,在第二个界面中也写一个Button,点击Button返回第一个界面

第一步建立一个工程以后在创建一个视图控制器,起名为SecondViewController。
第二步在第一个视图控制器写button,点击button跳转到下一界面

#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()

@end

@implementation ViewController
#pragma mark 视图将要出现
-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"视图将要出现");
}
#pragma mark 视图已经出现
-(void)viewDidAppear:(BOOL)animated{
     NSLog(@"视图已经出现");
}
#pragma  mark 视图已经出现
-(void)viewWillDisappear:(BOOL)animated{
    NSLog(@"视图已经出现");
}
#pragma  mark 视图已经消失
-(void)viewDidDisappear:(BOOL)animated{
    NSLog(@"视图已经消失");
}
#pragma mark - 
#pragma mark 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom ];
    button .frame = CGRectMake(100, 100, 100, 100);
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"按钮" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:  UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
}
-(void)buttonAction:(UIButton * )button{
    //创建一个要弹出的界面
    SecondViewController * secondViewControl = [[SecondViewController alloc]init];
    //UIModalTransitionStylePartialCurl:卷叶弹出 UIModalTransitionStyleFlipHorizontal:翻转弹出UIModalTransitionStyleCoverVertical:从下弹出(系统默认)
   secondViewControl.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    //参数1:弹出的界面 参数2:是否以动画的形式弹出 参数3:界面弹出完成之后要进行操作
    //presentViewController:适合弹出一些临时的窗口
    [self presentViewController:secondViewControl animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

第三步,在第二个视图控制器中定义Button,实现点击Button返回第一个界面

#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom ];
    button .frame = CGRectMake(100, 100, 100, 100);
    button.backgroundColor = [UIColor blueColor];
    [button setTitle:@"按钮" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:  UIControlEventTouchUpInside];
    [self.view addSubview:button];  
}
//模态
-(void)buttonAction:(UIButton *)button{
    //返回上一个界面
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(iOS-视图控制器)