Search code examples
iosswiftautolayout

autoResizingMask for inputAccessoryView not working


I'm trying to cope with iPhone X with inputAccessoryView. I've added a view to my ViewController like so:

CustomView

enter image description here

I've defined an outlet and attached to it. Returned the same view as inputAccessoryView like so:

class ViewController: UIViewController {

    @IBOutlet weak var textFieldContainer: UIView!

    override var inputAccessoryView: UIView? {
        return textFieldContainer
    }

    override var canBecomeFirstResponder: Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        textFieldContainer.autoresizesSubviews = true
    }
}

I've made sure to add constraints relative to safe area. Here are my constraints:

Constraints

enter image description here Adjusted autoResizingMask in SB like so:

AutoResizingMask

enter image description here

However, it's still not working. Here's the output:

Output

enter image description here

What did I miss?


Solution

  • Unlike for table view cells, there is no support for dynamic height calculation in input accessory views, as far as I know.

    You could use a fixed height for the accessory view.

    But I assume, that you want just to change either top, bottom, or height constraint in interface builder and the change is reflected after the next build.

    What you could do is, to use a custom view class where you connect your top, bottom and height constraints.

    Then override intrinsicContentSize and return the sum of the three constraint constants.

    class TextFieldContainer: UIView {
    
        @IBOutlet weak var topConstraint: NSLayoutConstraint!
        @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
        @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    
        override var intrinsicContentSize: CGSize {
    
            let contentHeight =
                self.topConstraint.constant
                    + self.heightConstraint.constant
                    + self.bottomConstraint.constant
    
            return CGSize(width: UIScreen.main.bounds.width, height: contentHeight)
        }
    }
    

    Your layout hierarchy could be simplified and look like this:

    view layout

    The autoresizing mask could look like this:

    autoresizing mask

    The final result would behave like the following then:

    input accessory view