UIViewController

来源:互联网 发布:沙丁鱼流量软件 编辑:程序博客网 时间:2024/05/01 02:10

UIViewController的用法方法和实现

首先创建一个新的根视图,并在视图中添加一定的布局

下面布局的button是为了跳转其他页面时用来写单击事件的

//铺一个buttonUIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];button.frame = CGRectMake(100, 500, 150, 40);[button setTitle:@"下一页" forState:UIControlStateNormal];self.view addSubview:button];[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];button.layer.borderWidth = 1;button.layer.cornerRadius = 10;

对应的button的点击事件

button的点击事件中创建了另一个视图控制器

在跳转之前要先引入所跳转的文件的头文件

-(void)click:(UIButton *)button{//下面是用来测试点击时背景颜色会随机切换    self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];//创建一个secondVC的对象SecondViewController *secondVC = [[SecondViewController alloc] init];//设置一下跳转的时候动画效果[secondVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];//进行跳转,这里的block不用需要添加代码,直接回车即可[self presentViewController:secondVC animated:YES completion:^{ }];//内存管理[secondVC release];}

下面的两段代码是用来实现视图上移的,当弹出键盘盖住了视图上的控件时,采用这种方式使整个界面上移,当回收键盘时,让界面归位

分别写在了-(BOOL)textFieldShouldBeginEditing:(UITextField )textField 开始编辑方法和-(BOOL)textFieldShouldEndEditing:(UITextField )textField 结束编辑方法(此处需要对textfield签协议)

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{//只要输入框被激活,就会触发这方法    if(textField.frame.origin.y > HEIGHT / 2){//先做一个差值        CGFloat height = textField.frame.origin.y - HEIGHT / 2;        self.view.center = CGPointMake(self.view.center.x, self.view.center.y - height);      }    return YES;}//等到编译结束的时候,让他回到原位-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{//整个是在移动self.view,父视图的移动会让所有的子视图一同移动,而且相对父视图的坐标位置不会发生变化,所以,可以沿用上一个方法的判断    if (textField.frame.origin.y > HEIGHT / 2) {        CGFloat height = textField.frame.origin.y - HEIGHT / 2;        self.view.center = CGPointMake(self.view.center.x, self.view.center.y + height);    }    return YES;}

下面是被跳转界面布局及内部方法

self.view.backgroundColor = [UIColor whiteColor];UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];button.frame = CGRectMake(100, 100, 100, 30);button.layer.borderWidth = 1;button.layer.cornerRadius = 10;[self.view addSubview:button];[button setTitle:@"返回" forState:UIControlStateNormal];[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

相对的跳转回原界面的点击方法

-(void)click:(UIButton *)button{//点击返回,回到前一个页面[self dismissViewControllerAnimated:YES completion:^{}];}
0 0
原创粉丝点击