效果图:

 

具体代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 30, 300, 300) textContainer:nil];
    //设置文本输入框的边界颜色
    textView.layer.borderColor = [UIColor blackColor].CGColor;
    //设置文本输入框的边界宽度
    textView.layer.borderWidth = 1.0f;
    //创建回收键盘的按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(0, 0, 320, 30);
    [button setTitle:@"收键盘.." forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
    //设置文本输入框的键盘控制器
    textView.inputAccessoryView = button;
    //设置文本输入框的tag
    textView.tag = 1001;
    [self.view addSubview:textView];
    
   

 //各位领导,inputAccessoryView是弹出键盘的上方的视图,至于触发事件有很多种方式,可以是按钮,可以是视图加了手势,可以是导航栏等等等,但是重点在触发事件内的写法以及inputAccessoryView这个属性..

下面这个方法特重要,键盘上来的时候可以使输入框自动上移

 [[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(keyboardChangedFrame:) name:UIKeyboardDidChangeFrameNotificationobject:nil];

}

-(void)keyboardChangedFrame:(NSNotification *)sender

{

    //键盘参数字典

    NSDictionary *userInfo=sender.userInfo;

    NSValue *value=[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

     CGRect endFrame=[value CGRectValue];

    UITextView *textView=(UITextView *)[self.viewviewWithTag:1001];

    CGRect textRect=textView.frame;

    

    CGFloat scale=endFrame.origin.y<480?1:-1;

    textRect.size.height-=scale*endFrame.size.height;

    textView.frame=textRect;

    

    NSLog(@"%@",sender);

}

- (void)didClickButton:(id)sender

{

    UITextView *textView = (UITextView *)[self.viewviewWithTag:1001];

    [textView resignFirstResponder];

}

 

假如我们用textField作为输入框的话,可以点击键盘return键实现隐藏键盘,需要引入协议<UITextFieldDelegate>

然后协议里面的方法就可以直接引用:

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

    UITextField *textField=[self.view viewWithTag:1001];//1001你声明UITextField对象之后赋值tag1001,通过tag找到这个textfield

    [textField resignFirstResponder];

}