ios How to add an inputAccessoryView?

Josh picture Josh · Dec 9, 2015 · Viewed 13.9k times · Source

I am trying to replicate Facebook Messenger App, where there is a UITextView attached to the top of the keyboard.

Due to the nature of this app I need my view to be attached, instead of manually scrolling up and down a ScrollView when the keyboard appears.

This can be achieved by using a inputAccessoryView.

I read the docs on it here.

The documentation is very brief and says:

"This property is typically used to attach an accessory view to the system-supplied keyboard that is presented for UITextField and UITextView objects.

The value of this read-only property is nil. If you want to attach custom controls to a system-supplied input view (such as the system keyboard) or to a custom input view (one you provide in the inputView property), redeclare this property as read-write in a UIResponder subclass.

You can then use this property to manage a custom accessory view. When the receiver becomes the first responder, the responder infrastructure attaches the accessory view to the appropriate input view before displaying it."

I have tried declaring a property

@interface CommentViewController ()
@property (nonatomic, readwrite, retain) UIView *inputAccessoryView;
@end

And then setting it:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 320, 100)];
    [view setBackgroundColor:[UIColor greenColor]];

    self.inputAccessoryView = view;

}

Then I have tried calling both of these:

  1. [self.tableView becomeFirstResponder];

  2. [view becomeFirstResponder];

Nothing happens. What am I doing wrong?

*Note - Extra information: I am using a UITableViewController that I want to have a UIView attached as an inputAccessoryView. Once I get the view working then I will add in a UITextView and more, but this is mainly an example.

Any help is greatly appreciated!

Answer

MadNik picture MadNik · Dec 9, 2015

Add input accessory to your textField or textView rather than to pure UIView.

self.mytextField.inputAccessoryView = view;