本例用UIView动画实现在编辑表单内容的时候表单上移一段距离的动画效果,以防止表单内容被弹出的输入键盘遮挡住。我们用Interface Builder来帮助我们布局,大体的页面结构是:根视图上丢一个UIImageView作为背景;丢一个UIView作为表单的载体,然后在在这个UIView上添加UITextField、UIButton等控件。然后在我们的主控制器中编写实现代码:
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextViewDelegate>
{
CGPoint formViewCenter; // 记录formView的起始位置
BOOL ifFormUp; // 表单是否已经上移
}
@property (nonatomic,retain) IBOutlet UIView *formView;
@property (nonatomic,retain) IBOutlet UITextField *usernametf;
@property (nonatomic,retain) IBOutlet UITextField *passwordtf;
- (IBAction)backgroundBtnClicked:(id)sender;
- (IBAction)registerBtnClicked:(id)sender;
- (IBAction)loginBtnClicked:(id)sender;
-(void)formUp; // 表单上移动画
-(void)formDown; // 表单下移动画
@end
#import "ViewController.h"
@implementation ViewController
@synthesize formView,usernametf,passwordtf;
#pragma mark - view life cycle
- (void)viewDidLoad
{
[super viewDidLoad];
formView.backgroundColor = [UIColor clearColor];
formViewCenter = formView.center;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
self.formView = nil;
self.usernametf = nil;
self.passwordtf = nil;
}
- (void)dealloc
{
self.formView = nil;
self.usernametf = nil;
self.passwordtf = nil;
[super dealloc];
}
#pragma mark - button actions
- (IBAction)backgroundBtnClicked:(id)sender
{
NSLog(@"Clicking_backgroundBtn");
if (ifFormUp) {
[usernametf resignFirstResponder];
[passwordtf resignFirstResponder];
[self formDown];
}
}
- (IBAction)registerBtnClicked:(id)sender
{
}
- (IBAction)loginBtnClicked:(id)sender
{
}
#pragma mark - form actions
// 表单上移
-(void)formUp
{
if(!ifFormUp)
{
ifFormUp = YES;
[UIView animateWithDuration:0.3 animations:^(void){
CGPoint newCenter = formViewCenter;
newCenter.y = 180.0f;
formView.center = newCenter;
}];
}
}
// 表单下移
-(void)formDown
{
if(ifFormUp)
{
ifFormUp = NO;
[UIView animateWithDuration:0.3 animations:^(void){
formView.center = formViewCenter;
}];
}
}
#pragma mark - UITextViewDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
if (!ifFormUp) {
[self formUp];
[textField becomeFirstResponder];
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[self formDown];
return YES;
}
@end
最终实现的效果如下:
源码下载:源码