天天看点

iOS中输入框被软键盘遮挡了怎么办?

看这个博客对于iOS中输入框被软键盘遮挡的回答,http://blog.csdn.net/enuola/article/details/7917221,感觉还是挺麻烦的,于是继续Google中,查到可以移动输入框来避免被键盘遮挡这一办法,于是自己试了试,真的蛮简单的,下面开始:

新建工程  Single view application

在ViewController.h 文件中声明协议

//
//  ViewController.h
//  TextFiled
//
//  Created by Ghost on 15-4-18.
//  Copyright (c) 2015年 Ghost. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>
@property(retain,nonatomic)UITextField * TextFiled;

@property(retain,nonatomic)UITextField * TextFiled1;
@end
           

在ViewController.m文件中

//
//  ViewController.m
//  TextFiled
//
//  Created by Ghost on 15-4-18.
//  Copyright (c) 2015年 Ghost. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _TextFiled  = [[UITextField alloc]init];
    _TextFiled.frame = CGRectMake(0, 100, 320, 50);
    _TextFiled.textColor = [UIColor redColor];
    _TextFiled.borderStyle = UITextBorderStyleRoundedRect;
    _TextFiled.font = [UIFont boldSystemFontOfSize:20];
    _TextFiled.delegate = self;
    [self.view addSubview:_TextFiled];
    
    _TextFiled1 = [[UITextField alloc]init];
    _TextFiled1.frame = CGRectMake(0, 300, 320, 50);
    _TextFiled1.textColor = [UIColor redColor];
    _TextFiled1.borderStyle = UITextBorderStyleRoundedRect;
    _TextFiled1.font = [UIFont boldSystemFontOfSize:20];
    _TextFiled1.delegate = self;
    [self.view addSubview:_TextFiled1];
    
    //手势收键盘(按空白的地方手下键盘)
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    
    //这两行代码是为了不让键盘挡住输入框
    //出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(show) name:UIKeyboardDidShowNotification object:nil];
    //收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hild) name:UIKeyboardDidHideNotification object:nil];
    
}

-(void)show{
    NSLog(@"出键盘");
    _TextFiled1.frame = CGRectMake(0, 150, 320, 50);
}

-(void)hild{
    NSLog(@"收键盘");
    _TextFiled1.frame = CGRectMake(0, 300, 320, 50);
}


//手势收键盘(按空白的地方手下键盘)
-(void)tapAction{
    [_TextFiled resignFirstResponder];
    [_TextFiled1 resignFirstResponder];
}


//按return收下键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == _TextFiled) {
        [_TextFiled resignFirstResponder];
        [_TextFiled1 resignFirstResponder];
    }else if (textField == _TextFiled1){
        [_TextFiled resignFirstResponder];
        [_TextFiled1 resignFirstResponder];
    }
    
    
    return YES;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
           

总结,其实就是把挡住的输入框往上面移动罢了