inputAccessoryView on UIView

4.6k views Asked by At

It's easy as pie to add an inputAccessoryView on a UITextField, UITextView, or UISearchBar. However, there's no obvious and easy way to add one for your basic UIView as far as I can tell!

I have a UIView subclass that follows the UIKeyInput protocol. It receives keyboard input to do stuff that isn't related to entering text, so I'd rather not force it to subclass the former specified views because it adds bloat and would expose a bunch of properties that don't do anything, plus I'd need to work around the text entry that occurs natively to those classes (more bloat).

However, my UIView does need an input accessory view on its presented keyboard to function correctly.

Are there any simple ways to go about this? Do I have to register as an observer to the UIKeyboardWillShowNotification in my UIView subclass and add a subview, as an accessory view, to it manually?

1

There are 1 answers

1
Darren On BEST ANSWER

Did you try simply adding the inputAccessoryView method to your viewController? I believe it gets called when the keyboard is shown, so you don't actually have to assign one to each textField or view.

- (UIView *)inputAccessoryView
{
    if (!inputAccessoryView)
    {
        CGRect accessFrame = CGRectMake(0.0, 0.0, 768.0, 77.0);
        inputAccessoryView = [[UIView alloc] initWithFrame:accessFrame];
        inputAccessoryView.backgroundColor = [UIColor blueColor];
        UIButton *compButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        compButton.frame = CGRectMake(313.0, 20.0, 158.0, 37.0);
        [compButton setTitle: @"Word Completions" forState:UIControlStateNormal];
        [compButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [compButton addTarget:self action:@selector(completeCurrentWord:) forControlEvents:UIControlEventTouchUpInside];
        [inputAccessoryView addSubview:compButton];
    }
    return inputAccessoryView;
}