Omotayo Oluwatobi Omotayo Oluwatobi - 1 month ago 18
iOS Question

Custom UIView that sticks to the keyboard in iOS objective-c

I want to make a custom UIView that sticks to the keyboard, I used input Accessory view, but it doesn't stay on my view controller when the keyboard is away. How can I have a UIView that I've constrained to the bottom of my view controller to stick to the keyboard (like the input accessory view) in iOS Objective-C?

Answer

Add an IBOutlet for bottomConstraint of the view. I assume it is a direct subview of ViewController's view and it should be on the bottom when keyboard is hidden.

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

Subscribe to keyboard notifications in viewWillAppear:

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.showKeyboard), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.hideKeyboard), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

Unsubscribe in viewDidDisappear:

NotificationCenter.removeObserver(self)

Later in your ViewController:

func showKeyboard(_ notification: NSNotification) {
    let info = notification.userInfo
    let rectValue = info![UIKeyboardFrameEndUserInfoKey] as? NSValue
    if let keyboardSize = rectValue?.cgRectValue.size {
        bottomConstraint.constant = (keyboardSize?.height)!
        view.layoutIfNeeded()
    }
}

func hideKeyboard(_ notification: Notification) {
    bottomConstraint.constant = 0
    view.layoutIfNeeded()
}

Objective-C:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)keyboardWillShow: (NSNotification *) notification {
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    _bottomConstraint.constant = keyboardSize.height;
    [view layoutIfNeeded];
}

-(void)keyboardWillHide: (NSNotification *) notification {
    _bottomConstraint.constant = 0;
    [view layoutIfNeeded];
}
Comments