lucgian841 lucgian841 - 1 year ago 131
Objective-C Question

Add UITextField above keyboard iOS

In my app I'm trying to add a UITextField on a accessoryView. It should work as follow:

  1. I press on a UITextField in the user interface of app

  2. The keyboard pop up and cover my UITextField on the user interface

  3. To edit text I wanted to show a UITextField in an accessoryView just above the keyboard

I looked on the web but I found only stuff to add button on an accessoryView, I hope you can help me to find a solution to add an UITextField on an accessoryView.

Thank you


This is what I mean:

enter image description here

I hope you understand better my question, I'm not looking for a solution that should user scroll view or something, I don't want to change the interface of my app...

Answer Source

in .h

UIView *customtoolbar;

in .m At viewdidload add thi code

customtoolbar=[[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height+50, 320, 50)];`

after this add this methods

 -(BOOL)textFieldShouldReturn:(UITextField *)textField{

    [self pressdone];

    return YES;

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

        //216 is keyboard default height in portrait(162 in landscape)
    [UIView animateWithDuration:0.7 animations:^{
    [self addtoolbar:CGRectMake(0, self.view.frame.size.height-216-50, 320, 50)];

    return YES;
-(UIView *)addtoolbar:(CGRect )frame{

    customtoolbar.backgroundColor=[UIColor darkGrayColor];

    //give new frame to your textfield
    txtfld.frame=CGRectMake(5,10, 220, 30);
    [customtoolbar addSubview:txtfld];

    UIButton *done=[UIButton buttonWithType:UIButtonTypeCustom];
    done.frame=CGRectMake(235,10, 60, 30);
    [done setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [done setTitle:@"Done" forState:UIControlStateNormal];
    [done addTarget:self  action:@selector(pressdone) forControlEvents:UIControlEventTouchUpInside];
    [customtoolbar addSubview:done];
    [self.view addSubview:customtoolbar];

    return customtoolbar;


    [self addtoolbar:CGRectMake(0, self.view.frame.size.height+50, 320, 50)];

    //set there orignal frame of your textfield
    txtfld.frame=CGRectMake(95, 170, 123, 37);
    [self.view addSubview:txtfld];
    [txtfld resignFirstResponder];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download