UIToolbar for keyboard inputAccessoryView gives Layout Constraint Errorsby
UIToolbar is very useful control for our input fields for example when we need some action buttons above keypad for input whose keypad type is UIKeyboardType.phonePad. UIKeyboardType.phonePad doesn’t come up with any return key button to dismiss as of now. A simple UIToolbar is very sufficient to provide a button for user to dismiss or do something else.
UIToolbarA control that displays one or more buttons along the bottom edge of your interface.
The simple code to add UItoolbar to textfield:
let flexibleButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) let done = UIBarButtonItem(title: "Dismiss", style: .done, target: self, action: #selector(doneKeypadTapped)) let bar = UIToolbar() bar.items = [flexibleButton, done] bar.sizeToFit() phonePadTextfield.inputAccessoryView = bar
Now above code does give layout-constraints error indicating that few constraints are not satisfying each other and breaking the layout. It will not break the app in the sense but it does give sense of unease to a developer.
Small snippet from the contraint-error:
<NSLayoutConstraint:0x6000023bec60 ‘TB_Trailing_Trailing’ H:[_UIModernBarButton:0x7fb8bb990f20’Dismiss’]-(20)-| (active, names: ‘|’:_UIButtonBarButton:0x7fb8bb98e100 )>
The simple solution was to initialise the UIToolbar with frame instead of empty initialiser. With frames provided, auto layout constraints gets to work on more concrete dimension to satisfy the constraints.
let bar = UIToolbar(frame:CGRect(x:0, y:0, width:100, height:44))
You might also like: How to Send Local Video to iMessage in Swift
You might also like: AVAudioPlayer not playing any sound
You might also like: How to Get Substring With NSRange in Swift 5
You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2