How to programmatically add InputAccessoryView with Autolayout?

I am trying to add a UIView with a Finish button as a kind of auxiliary input in a text box.

  let view = UIView() let doneButton = UIButton(type: .Custom) doneButton.setTitle("Done", forState: .Normal) doneButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(doneButton) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[button]-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["button":doneButton])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button]|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["button":doneButton])) view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: doneButton, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)) // Even this does not work self.emailTextField.inputAccessoryView = view 

But, however, I do not see the height setting of the view and buttons in the debugger / inspector of the hierarchy view in Xcode.

But if I add a view by setting its frame, I will see the addition of a view. I also tried to force the height limit to constant 21, and it violated some other restrictions that I did not add _UIKBAutolayoutHeightConstraint

 "<NSLayoutConstraint:0x7fa3c962be50 UIView:0x7fa3c963bf60.height == UIButton:0x7fa3c963c0d0.height + 21>", "<NSLayoutConstraint:0x7fa3c95e0a90 '_UIKBAutolayoutHeightConstraint' V:[UIView:0x7fa3c963bf60(0)]>" 

Has anyone encountered this problem before?

+6
source share
1 answer

Swift 3+

  • You need to specify the size of the toolbar in the first line.
  • Do not use 'view' as a variable in the viewcontroller class, as it creates confusion vs self.view

     override func viewDidLoad() { super.viewDidLoad() let toolBar = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 50)) toolBar.backgroundColor = .gray let doneButton = UIButton(type: .custom) doneButton.setTitle("Done", for: .normal) doneButton.translatesAutoresizingMaskIntoConstraints = false toolBar.addSubview(doneButton) toolBar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[button]-|", options: .directionLeadingToTrailing, metrics: nil, views: ["button":doneButton])) toolBar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[button]|", options: .directionLeadingToTrailing, metrics: nil, views: ["button":doneButton])) self.emailTextField.inputAccessoryView = toolBar } 
0
source

All Articles