iosswiftuiviewcontrollerinputaccessoryview

How can I show the inputAccessoryView in this view controller


I have a function in my controller I call

private func toggleLauncher() {
    let launcher = CommentsLauncher()
    launcher.showLauncher()
}

This essentially adds a view on top of the current view, with a semi transparent background.

I'd like to then render a custom inputAccessoryView at the bottom of the newly added view.

class CommentsLauncher: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(white: 0, alpha: 0.5)
    }

    func showLauncher() {
         if let window = UIApplication.shared.keyWindow {
            window.addSubview(view)
        }
    }

    override var inputAccessoryView: UIView? {
        get {
            let containerView = UIView()
            containerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
            containerView.backgroundColor = .purple
            return containerView
        }
    }

    override var canBecomeFirstResponder: Bool {
        return true
    }
}

All that happens though is the semi transparent background is visible but I see no inputAccessoryView added to the view also and I am unsure why.


Solution

  • Your CommentsLauncher never become the first responder in the code you provided. A UIResponder's inputAccessoryView is displayed when the responder becomes first responder.

    Change your showLauncher method to something like this:

    func showLauncher() {
        if let window = UIApplication.shared.keyWindow {
            window.addSubview(view)
            becomeFirstResponder()
        }
    }
    

    And you should see the input accessory view.